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

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
}
▶ RUN Output/ Explanation: 