Programming Examples

Arduino program to interface a servo motor and a button at pin 7


O level January 2025 practical Exam question

Write a program to interface a servo motor and a button at pin 7. On each button press, rotate the servo motor by 45 degrees incrementally until it completes a 180- degree rotation. After reaching 180 degrees, reset it to 0 degrees on the next press.

Solution

#include <Servo.h>  // Include the Servo library

Servo myServo;       // Create a Servo object
int angle = 0;       // Current angle of the servo
int lastButtonState = LOW;  // Previous button state
int buttonState;            // Current button state

void setup() {
  pinMode(7, INPUT);  // Button with internal pull-up
  myServo.attach(9);          // Attach servo to pin
  myServo.write(angle);               // Initialize servo at 0 degrees
  Serial.begin(9600);
}

void loop() {
  buttonState = digitalRead(7);

  // Detect button press (change from HIGH to LOW)
  if (buttonState == LOW && lastButtonState == HIGH) 
  {
    // Increment angle by 45 degrees
    angle += 45;

    // Reset to 0 if angle exceeds 180
    if (angle > 180) {
      angle = 0;
    }

    myServo.write(angle);  // Move servo to new angle
    Serial.print("Servo Angle: ");
    Serial.println(angle);

    delay(200); // Simple debounce delay
  }

  lastButtonState = buttonState;  // Update last button state
}
Output


Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad