#include <Servo.h>
Servo myservo; // create servo object to control a servo
// Constants for pin assignments
const int buttonPin1 = 2; // pin connected to the left-turn button
const int buttonPin2 = 3; // pin connected to the right-turn button
const int ledPin = 13; // pin connected to the LED
const int servoPin = 9; // pin connected to the Servo
// Function prototypes
void turnLeft();
void turnRight();
// Variables to store the servo position and the last debounce times
int servoPos = 90; // start at mid-point, 90 degrees
unsigned long lastDebounceTime1 = 0; // last debounce time for button 1
unsigned long lastDebounceTime2 = 0; // last debounce time for button 2
unsigned long debounceDelay = 50; // the debounce time in milliseconds
void setup() {
myservo.attach(servoPin); // attaches the servo on the specified pin to the servo object
pinMode(ledPin, OUTPUT); // sets the LED pin as output
pinMode(buttonPin1, INPUT_PULLUP); // sets the left-turn button pin as input with internal pull-up
pinMode(buttonPin2, INPUT_PULLUP); // sets the right-turn button pin as input with internal pull-up
myservo.write(servoPos); // centers the servo
digitalWrite(ledPin, LOW); // ensures the LED is off to start
// Set up interrupts for button presses
attachInterrupt(digitalPinToInterrupt(2), turnLeft, FALLING);
attachInterrupt(digitalPinToInterrupt(3), turnRight, FALLING);
}
void loop() {
// Nothing to do here
}
void turnLeft() {
if ((millis() - lastDebounceTime1) > debounceDelay) {
if (servoPos >= 10) { // Check if the position is greater than or equal to 10
servoPos -= 10; // Decreases the position by 10 degrees
myservo.write(servoPos); // Move servo to new position
lastDebounceTime1 = millis();
}
updateLED(); // Update the LED status based on new position
}
}
void turnRight() {
if ((millis() - lastDebounceTime2) > debounceDelay) {
if (servoPos <= 170) { // Check if the position is less than or equal to 170
servoPos += 10; // Increases the position by 10 degrees
myservo.write(servoPos); // Move servo to new position
lastDebounceTime2 = millis();
}
updateLED(); // Update the LED status based on new position
}
}
void updateLED() {
// Turn on the LED if the servo is at 0 or 180 degrees, otherwise turn it off
if (servoPos == 0 || servoPos == 180) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}