#include <Servo.h>
// Servo motor control and pushbutton pins
const int servoPin = 9;
const int switchOnPin = 2;
const int switchSpeedPin = 3;
const int switchOffPin = 4;
// Servo motor object
Servo myServo;
// Variables to control servo speed
int servoSpeed = 0; // Default speed
bool motorOn = false; // Servo motor state
void setup() {
// Initialize the servo motor
myServo.attach(servoPin);
myServo.write(0); // Set initial position
// Set up the switch pins as inputs with pull-up resistors
pinMode(switchOnPin, INPUT_PULLUP);
pinMode(switchSpeedPin, INPUT_PULLUP);
pinMode(switchOffPin, INPUT_PULLUP);
}
void loop() {
// Check if the "turn on" switch is pressed
if (digitalRead(switchOnPin) == LOW) {
motorOn = true;
servoSpeed = 5; // Default constant speed
}
// Check if the "change speed" switch is pressed
if (digitalRead(switchSpeedPin) == LOW && motorOn) {
servoSpeed = 10; // Change to a higher speed
}
// Check if the "turn off" switch is pressed
if (digitalRead(switchOffPin) == LOW) {
motorOn = false;
servoSpeed = 0;
myServo.write(0); // Reset servo position
}
// Control the servo motor if it is on
if (motorOn) {
for (int pos = 0; pos <= 180; pos += servoSpeed) {
myServo.write(pos); // Move servo to position
delay(20); // Delay for smooth movement
}
for (int pos = 180; pos >= 0; pos -= servoSpeed) {
myServo.write(pos); // Move servo back
delay(20); // Delay for smooth movement
}
}
}