#include <Servo.h>
Servo myservo; // create servo object to control a servo
int buttonPin = 2; // the pin that the pushbutton is attached to
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable to store the button state
int servoPositions[3] = {0, 90, 180}; // array to store the servo positions
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(buttonPin, INPUT); // sets the digital pin 2 as input
}
void loop() {
buttonState = digitalRead(buttonPin); // read the state of the pushbutton
if (buttonState == HIGH) { // if button is pressed
pos++; // increment the position
if (pos >= 3) { // if position is out of bounds, reset to 0
pos = 0;
}
myservo.write(servoPositions[pos]); // set the servo position based on the current position index
delay(1000); // wait for 1 second to allow the servo to move to the new position
}
}
Comments
Please log in or sign up to comment.