#include <Keypad.h>
#include <ESP32Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define ROWS 4
#define COLS 4
const int sensorpin = 26;
int initialstate= LOW;
int finalstate = LOW;
const int ledpin=33;
const int timeout=20000;
int errorcount=0;
int initialtime=0;
int finaltime=0;
int count=1;
bool inputTimeoutReached = false;
String passcode="5090";
const int buzzer=32;
LiquidCrystal_I2C lcd(0x27,16,2);
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowpins[ROWS] = {4, 5, 18, 19};
byte colpins[COLS] = {15, 14, 27, 23};
String inpString="";
Keypad keypad = Keypad( makeKeymap(keys), rowpins, colpins, ROWS, COLS);
Servo motor;
void setup() {
Serial.begin(9600);
lcd.backlight();
lcd.init();
pinMode(sensorpin,OUTPUT);
pinMode(ledpin,OUTPUT);
motor.attach(2,500,2400);
}
void loop() {
motionCheck();
pinInput();
}
void pinInput(){
lcd.setCursor(0,0);
lcd.print("ENTER PASSKEY:");
while(inpString.length()!=4){
char key=keypad.getKey();
if (key) {
inpString+=key;
lcd.setCursor(inpString.length()-1,1);
lcd.print(inpString[inpString.length()-1]);
}
if (inpString.length()==1) {
finaltime = millis();
}
if (finaltime-initialtime>timeout) {
inputTimeoutReached = true;
initialtime=finaltime+count*20000;
count++;
}
break;
}
if (inputTimeoutReached) {
// Reset variables after input or timeout
lcd.clear();
inpString = "";
inputTimeoutReached = false;
}
if (inpString.length() == 4) {
if(inpString==passcode){
digitalWrite(2, HIGH);
motor.writeMicroseconds(1500);
errorcount=0;
tone(buzzer, 300, 250);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("UNLOCKED");
delay(3000);
}
else{
errorcount+=1;
digitalWrite(2,LOW);
motor.writeMicroseconds(1000);
tone(buzzer, 262, 250);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("INCORRECT");
delay(3000);
if(errorcount==3){
Serial.println("CAUTION");
digitalWrite(buzzer, HIGH);
delayMicroseconds(25000);
digitalWrite(buzzer, LOW);
errorcount=0;
}
}
// Reset variables after input or timeout
inpString = "";
inputTimeoutReached = false;
}
}
void motionCheck(){
initialstate = finalstate;
finalstate = digitalRead(sensorpin);
if (initialstate == LOW && finalstate == HIGH){
Serial.println("Motion detected!");
digitalWrite(ledpin,HIGH);
}
else
if (initialstate == HIGH && finalstate == LOW){
Serial.println("Motion stopped!");
digitalWrite(ledpin,LOW);
}
}