#include <Keypad.h>
#include <EEPROM.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD and Keypad Initialization
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte rows = 4;
const byte columns = 4;
char hexaKeys[rows][columns] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte row_pins[rows] = {2, 3, 4, 5};
byte column_pins[columns] = {6, 7, 8, 9};
Keypad keypad_key = Keypad(makeKeymap(hexaKeys), row_pins, column_pins, rows, columns);
char inputPIN[5]; // To store the entered PIN
char storedPIN[5] = "1234"; // Default PIN
int relayPin = 11; // Relay connected to pin 11
int attemptIndex = 0; // Keeps track of the PIN entry progress
void setup() {
lcd.begin(16, 2); // Initialize LCD with 16 columns and 2 rows
lcd.backlight();
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // Ensure relay starts off (locked)
lcd.print("Electronic Lock");
delay(2000);
lcd.clear();
lcd.print("Enter PIN:");
}
void loop() {
char key = keypad_key.getKey();
if (key) {
// If a key is pressed, display it and store the input
lcd.setCursor(attemptIndex, 1);
lcd.print("*"); // Hide the actual input for security
inputPIN[attemptIndex++] = key;
// When 4 digits are entered, process the input
if (attemptIndex == 4) {
inputPIN[4] = '\0'; // Null-terminate the input
if (strcmp(inputPIN, storedPIN) == 0) {
// PIN is correct
lcd.clear();
lcd.print("Access Granted");
digitalWrite(relayPin, LOW); // Unlock the door
delay(5000); // Keep the relay open for 5 seconds
digitalWrite(relayPin, HIGH); // Lock the door
lcd.clear();
lcd.print("Enter PIN:");
} else {
// PIN is incorrect
lcd.clear();
lcd.print("Access Denied");
delay(2000);
lcd.clear();
lcd.print("Enter PIN:");
}
attemptIndex = 0; // Reset input index
}
}
// Change PIN function if '#' is pressed
if (key == '#') {
changePIN();
}
}
// Function to change the stored PIN
void changePIN() {
char currentPIN[5], newPIN[5];
int index = 0;
lcd.clear();
lcd.print("Current PIN:");
while (index < 4) {
char key = keypad_key.getKey();
if (key) {
lcd.setCursor(index, 1);
lcd.print("*"); // Hide input
currentPIN[index++] = key;
}
}
currentPIN[4] = '\0'; // Null-terminate
if (strcmp(currentPIN, storedPIN) != 0) {
// Incorrect current PIN
lcd.clear();
lcd.print("Wrong PIN");
delay(2000);
lcd.clear();
lcd.print("Enter PIN:");
return;
}
// Ask for new PIN
lcd.clear();
lcd.print("New PIN:");
index = 0;
while (index < 4) {
char key = keypad_key.getKey();
if (key) {
lcd.setCursor(index, 1);
lcd.print("*"); // Hide input
newPIN[index++] = key;
}
}
newPIN[4] = '\0'; // Null-terminate
// Save new PIN to memory
strcpy(storedPIN, newPIN);
lcd.clear();
lcd.print("PIN Changed");
delay(2000);
lcd.clear();
lcd.print("Enter PIN:");
}