#include <Servo.h>
Servo myservo;
const int button_pin = 4;
bool last_button_state = HIGH;
bool current_button_state;
bool servo_toggled = false;
unsigned long last_debounce_time = 0;
const unsigned long debounce_delay = 50;
void setup() {
myservo.attach(9);
pinMode(button_pin, INPUT_PULLUP);
myservo.write(0); // Start at 0 degrees
}
void loop() {
int reading = digitalRead(button_pin);
// Check for state change with debounce
if (reading != last_button_state) {
last_debounce_time = millis();
}
if ((millis() - last_debounce_time) > debounce_delay) {
if (reading != current_button_state) {
current_button_state = reading;
// If button is pressed (LOW because of INPUT_PULLUP)
if (current_button_state == LOW) {
servo_toggled = !servo_toggled;
if (servo_toggled) {
myservo.write(90);
} else {
myservo.write(0);
}
}
}
}
last_button_state = reading;
}