#include <Servo.h>
// Define pin connections and constants
#define SWITCH_PIN 8 // Pin connected to the switch
#define SERVO_PIN 3 // Pin connected to the servo motor
Servo myServo;
// Servo angles for open and close positions
const int CLOSE_ANGLE = 0;
const int OPEN_ANGLE = 90;
// Variables for the servo angle and debouncing
int currentAngle = CLOSE_ANGLE;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
// Initialize the switch pin and servo
pinMode(SWITCH_PIN, INPUT);
myServo.attach(SERVO_PIN);
myServo.write(currentAngle); // Start with the servo in the closed position
}
void loop() {
// Read the state of the switch
int switchState = digitalRead(SWITCH_PIN);
// Debounce logic to ensure stable input reading
if (millis() - lastDebounceTime > debounceDelay) {
if (switchState == HIGH) {
currentAngle = OPEN_ANGLE; // Open the servo
} else {
currentAngle = CLOSE_ANGLE; // Close the servo
}
lastDebounceTime = millis(); // Update debounce time
}
// Write the angle to the servo
myServo.write(currentAngle);
// Add a small delay to avoid rapid toggling
delay(200);
}