#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 5, 4, 3, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 }; // Pins connected to R1, R2, R3, R4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
lcd.setCursor(3, 0);
unlocked();
}
bool isDoorLocked=false;
void loop() {
if(isLocked()){
locked();
}else{
unlocked();
}
}
String newpass="";
String savedPass="";
bool isPassSet=false;
String setPass(){
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Enter Pass");
lcd.setCursor(7, 1);
lcd.print("< >");
lcd.setCursor(8, 1);
while (newpass.length() < 4) {
char key = keypad.getKey();
if (key<='9' && key>='0') {
lcd.print(key);
newpass+=key;
}
}
if(newpass.length()==4 ){
isPassSet=true;
}
return newpass;
}
bool isSet(){
if(isPassSet){
return true;
}
return false;
}
void checkPass(String pass){
lcd.setCursor(0, 2);
if(pass==savedPass){
unlocked();
}else if(pass!=savedPass){
locked();
}
}
bool isLocked(){
if(isDoorLocked){
return true;
}
return false;
}
void locked(){
isDoorLocked=true;
lcd.clear();
lcd.setCursor(1,1);
lcd.print("The Door is Locked");
lcd.setCursor(0,1);
lcd.print("Enter pass to unlock");
String pass=setPass();
checkPass(pass);
}
void unlocked(){
lcd.clear();
isDoorLocked=false;
if(isSet()){
lcd.setCursor(1,0);
lcd.print("'*' to reset pass");
lcd.setCursor(4,1);
lcd.print("'#' to lock");
lcd.setCursor(18,1);
char key = keypad.getKey();
if (key=='*') {
lcd.clear();
setPass();
}else if(key=='#'){
locked();
}
}else {
savedPass=setPass();
}
}