#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
Servo myServo;
#define SERVO_PIN 10
String password = "";
String inputPassword = "";
bool isPasswordSet = false;
void setup() {
lcd.begin(20, 4);
myServo.attach(SERVO_PIN);
myServo.write(0);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("System Ready");
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == 'A') {
setPassword();
} else if (key == 'B') {
resetPassword();
} else if (key == 'C') {
backspace();
} else if (key == 'D') {
verifyPassword();
} else {
inputPassword += key;
lcd.setCursor(inputPassword.length() - 1, 1);
lcd.print("*");
}
}
}
void setPassword() {
lcd.clear();
if (isPasswordSet) {
lcd.print("Password Exists");
delay(2000);
} else {
lcd.print("Set Password:");
inputPassword = "";
while (inputPassword.length() < 4) {
char key = keypad.getKey();
if (key) {
inputPassword += key;
lcd.setCursor(inputPassword.length() - 1, 1);
lcd.print("*");
}
}
password = inputPassword;
inputPassword = "";
isPasswordSet = true;
lcd.clear();
lcd.print("Password Saved");
delay(2000);
}
lcd.clear();
lcd.print("Enter Password:");
}
void resetPassword() {
lcd.clear();
if (!isPasswordSet) {
lcd.print("Set Password 1st");
delay(2000);
} else {
lcd.print("Enter Old Pass:");
inputPassword = "";
while (inputPassword.length() < 4) {
char key = keypad.getKey();
if (key) {
inputPassword += key;
lcd.setCursor(inputPassword.length() - 1, 1);
lcd.print("*");
}
}
if (inputPassword == password) {
lcd.clear();
lcd.print("Set New Pass:");
inputPassword = "";
while (inputPassword.length() < 4) {
char key = keypad.getKey();
if (key) {
inputPassword += key;
lcd.setCursor(inputPassword.length() - 1, 1);
lcd.print("*");
}
}
password = inputPassword;
inputPassword = "";
lcd.clear();
lcd.print("Password Reset");
delay(2000);
} else {
lcd.clear();
lcd.print("Incorrect Pass");
delay(2000);
}
}
lcd.clear();
lcd.print("Enter Password:");
}
void backspace() {
if (inputPassword.length() > 0) {
inputPassword.remove(inputPassword.length() - 1);
lcd.setCursor(inputPassword.length(), 1);
lcd.print(" ");
lcd.setCursor(inputPassword.length(), 1);
}
}
void verifyPassword() {
lcd.clear();
if (inputPassword == password) {
lcd.print("Unlocked");
myServo.write(90);
delay(5000);
myServo.write(0);
} else {
lcd.print("Wrong Password");
delay(2000);
}
inputPassword = "";
lcd.clear();
lcd.print("Enter Password:");
}