#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
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] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
const int passwordLength = 4;
char password[passwordLength];
char enteredPassword[passwordLength];
void setup() {
lcd.backlight();
lcd.init();
pinMode(13, OUTPUT); // Lock output
setNewPassword();
}
void loop() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter code:");
checkCode();
}
void setNewPassword() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Set password:");
for (int i = 0; i < passwordLength; ++i) {
char key = getKey();
password[i] = key;
lcd.setCursor(i, 1);
lcd.print('*');
delay(500);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Type code:");
}
void checkCode() {
for (int i = 0; i < passwordLength; ++i) {
char key = getKey();
enteredPassword[i] = key;
lcd.setCursor(i, 1);
lcd.print('*');
delay(500);
}
if (checkPassword()) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You won!");
digitalWrite(13, HIGH); // Lock
delay(2000);
digitalWrite(13, LOW); // Unlock
setNewPassword();
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("You lost!");
delay(2000);
setNewPassword();
}
}
bool checkPassword() {
for (int i = 0; i < passwordLength; ++i) {
if (enteredPassword[i] != password[i]) {
return false;
}
}
return true;
}
char getKey() {
char key = customKeypad.getKey();
while (!key) {
key = customKeypad.getKey();
}
return key;
}