#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include<ESP32Servo.h>
#include <WiFi.h>
char ssid[] = "Wokwi-GUEST";
char password[] = "";
Servo servo;
#define BUZZER 4
#define trigPin 23
#define echoPin 19
int otp;
String otpstring = "";
int i = 0;
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
byte rowPins[ROWS] = { 12,14,27,26};
byte colPins[COLS] = { 25,33,32,35};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
long distance;
void setup()
{
Serial.begin(115200);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.print("CONNECTING TO...");
lcd.setCursor(0,1);
lcd.print(ssid);
delay(1000);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while(WiFi.status()!= WL_CONNECTED)
{
Serial.print('.');
delay(500);
}
Serial.println("READY");
lcd.clear();
lcd.print(" WIFI CONNECTED ");
Serial.print(" WIFI CONNECTED ");
pinMode(BUZZER,OUTPUT);
digitalWrite(BUZZER,LOW);
lcd.clear();
lcd.print(" WIFI CONNECTED ");
delay(2000);
servo.attach(4);
servo.write(90);
delay(500);
}
void loop() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("OTP BASED DOOR");
lcd.setCursor(0, 1);
lcd.print("LOCK USING IOT");
// Check if someone is near the door using ultrasonic sensor
measureDistance();
if (distance <= 200) {
activateAlarm();
} else {
deactivateAlarm();
}
char key = customKeypad.getKey();
if (key) {
if (isDigit(key) || key == '*') {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter OTP:");
getotp();
}
}
}
void activateAlarm() {
digitalWrite(BUZZER, HIGH); // Turn on the buzzer
}
void deactivateAlarm() {
digitalWrite(BUZZER, LOW); // Turn off the buzzer
}
void measureDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
distance = pulseIn(echoPin, HIGH) * 0.034 / 2; // Calculate distance in cm
}
void getotp() {
String y = "";
int a = y.length();
while (a < 4) {
char customKey = customKeypad.getKey();
if (customKey)
{
lcd.setCursor(0, 1);
y = y + customKey;
lcd.print(y);
a = y.length();
}
}
Serial.print("Entered OTP is ");
Serial.println(y);
if (otpstring == y) {
lcd.setCursor(0, 0);
lcd.print("Access Granted");
lcd.setCursor(0, 1);
lcd.print("Door Opening");
delay(2000);
lcd.clear();
lcd.print("* WELCOME *");
delay(3000);
for(i=90;i>=0;i--)
{
servo.write(i);
delay(15);
}
delay(10000);
for(i=0;i<=90;i++)
{
servo.write(i);
delay(15);
}
}
else
{
lcd.setCursor(0, 0);
lcd.print("Access Failed");
lcd.setCursor(0, 1);
lcd.print("Try Again !!!");
digitalWrite(BUZZER,HIGH);
delay(2000);
digitalWrite(BUZZER,LOW);
delay(3000);
}
}