#include <ESP32Servo.h>
#include <LiquidCrystal_I2C.h>
#define SERVO_PIN 5 // Replace with the GPIO pin connected to the servo
#define PIR_PIN 25
bool doorLocked = true; // Initial door locked state
bool motionDetected = false;
Servo doorLock; // Create a servo object
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
doorLock.attach(SERVO_PIN); // Attach the servo to the specified pin
pinMode(PIR_PIN, INPUT);
doorLock.write(0);
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Motion Detector");
}
void loop() {
motionDetected = digitalRead(PIR_PIN); // Check for motion
if (motionDetected) {
if (doorLocked) {
unlockDoor();
} else {
lockDoor();
}
delay(1000); // Delay to avoid continuous detection
}
}
void unlockDoor() {
doorLocked = false;
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Motion Detected");
LCD.setCursor(0, 1);
LCD.print("Door Unlocked");
doorLock.write(90); // Unlock the door (servo movement)
delay(5000); // Door remains unlocked for 5 seconds
doorLocked = true;
lockDoor();
}
void lockDoor() {
doorLock.write(0); // Lock the door (servo movement)
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Door Locked");
}