#include <Servo.h>
Servo myServo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
// Pin definitions
const int servoPin = 9;
const int buttonPin = 2;
// Variables for button state
int buttonState = 0;
int lastButtonState = 0;
int currentSpeed = 1;
// Speeds in milliseconds per degree
int speedSettings[3] = {15, 10, 5}; // Slow, Medium, Fast
void setup() {
myServo.attach(servoPin); // attaches the servo on pin 9 to the servo object
pinMode(buttonPin, INPUT_PULLUP); // Initialize the pushbutton pin as an input with pullup resistor
}
void loop() {
buttonState = digitalRead(buttonPin);
// Check if the button was pressed
if (buttonState == LOW && lastButtonState == HIGH) {
// Increment the speed setting
currentSpeed++;
if (currentSpeed > 3) {
currentSpeed = 1; // Roll over to the first speed setting
}
delay(250); // Debounce delay
}
lastButtonState = buttonState;
// Move the servo
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
myServo.write(pos); // tell servo to go to position in variable 'pos'
delay(speedSettings[currentSpeed - 1]); // wait for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myServo.write(pos); // tell servo to go to position in variable 'pos'
delay(speedSettings[currentSpeed - 1]); // wait for the servo to reach the position
}
}