#include <Servo.h>
// Create Servo object
Servo myServo;
// Define pins
const int buttonPin = 2; // Button connected to D2
const int servoPin = 9; // Servo connected to D9
const int redLedPin = 3; // Red LED connected to D3
const int greenLedPin = 4; // Green LED connected to D4
// Variables
int buttonState = 0; // To store current button state
int lastButtonState = 0; // To store previous button state
unsigned long lastDebounceTime = 0; // Time of the last button state change
unsigned long debounceDelay = 50; // Debounce delay in milliseconds
bool isDoorOpen = false; // Track door status
void setup() {
// Configure pins
pinMode(buttonPin, INPUT);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
// Initialize Servo and LEDs
myServo.attach(servoPin);
closeDoor();
Serial.begin(9600);
// For debugging
}
void loop() {
// Read the current button state
int reading = digitalRead(buttonPin);
// If the button state has changed (pressed or released)
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset debounce timer
}
// If enough time has passed since the last button change (debounced)
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed and is stable, proceed
if (reading != buttonState) {
buttonState = reading;
// Only take action if the button is pressed (HIGH)
if (buttonState == HIGH) {
if (isDoorOpen) {
Serial.println("CLOSE DOOR INSIDE LOOP");
closeDoor();
} else {
Serial.println("OPEN DOOR INSIDE LOOP");
openDoor();
}
}
}
}
// Save the current button state for the next loop
lastButtonState = reading;
}
void openDoor() {
myServo.write(180); // Move servo to 180° (open position)
digitalWrite(greenLedPin, HIGH); // Turn on green LED
digitalWrite(redLedPin, LOW); // Turn off red LED
isDoorOpen = true; // Update door state
Serial.println("Door Opened");
delay(2000); // Give time for the door to fully open
closeDoor(); // Automatically close the door after opening
}
void closeDoor() {
myServo.write(0); // Move servo to 0° (closed position)
digitalWrite(redLedPin, HIGH); // Turn on red LED
digitalWrite(greenLedPin, LOW); // Turn off green LED
isDoorOpen = false; // Update door state
Serial.println("Door Closed");
}