#include <ESP32Servo.h>
// Import the required library to setup the LCD
#include <LiquidCrystal_I2C.h>
#define SERVO_PIN 14
#define PIR_PIN 25
#define BUZZER_PIN 19
bool motionDetected = false;
// Declare the flag variable doorLocked and set intial value to false
bool doorLocked = true;
Servo doorLock;
// Setup the LCD
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
doorLock.attach(SERVO_PIN);
doorLock.write(0);
// Initilise the display and display the message
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Smart Door Lock");
}
void loop() {
motionDetected = digitalRead(PIR_PIN);
if (motionDetected) {
// Check whether the door is locked or not. Accordingly, call unlock the door and lock the door functions.
if(doorLocked){
unlockDoor();
}else{
lockDoor();
}
}
delay(200);
}
void unlockDoor() {
// Set doorLocked value to false
doorLocked = false;
// Display the message "Motion Detected Door Unlokced"
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Motion Detected");
LCD.setCursor(0, 1);
LCD.print("Door Unlocked");
doorLock.write(90);
tone(BUZZER_PIN, 1000);
delay(300);
tone(BUZZER_PIN, 0);
// Door remains unlocked for 5 seconds
delay(5000);
// After 5 seconds set the doorLocked value to true and call lockDoor function
doorLocked = true;
lockDoor();
}
void lockDoor() {
doorLock.write(0);
// Display the message "Door Lokced"
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Door Locked");
}