#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h> // Include Keypad library
// Define LCD I2C address
const int lcd_I2C_address = 0x27;
// Define LCD size
const int lcd_columns = 16;
const int lcd_rows = 2;
LiquidCrystal_I2C lcd(lcd_I2C_address, lcd_columns, lcd_rows);
// Keypad configuration (adjust rows and columns based on your keypad)
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] = {19, 18, 5, 17};
byte colPins[COLS] = {16, 4, 0, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define door state variables
bool doorIsOpen = false;
bool doorIsLocked = true; // Initial state
// Define your correct door unlock code (replace with your desired sequence)
const char correctCode[] = "1234";
int codeLength = sizeof(correctCode) - 1; // Calculate code length (excluding null terminator)
int enteredChars = 0;
char enteredCode[codeLength]; // Array to store entered keypad digits
void setup() {
Serial.begin(115200); // Initialize serial communication for debugging
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.clear();
// Display initial door state
lcd.print("Door: ");
updateDoorStatus();
}
void loop() {
char enteredCode[codeLength];
char key = keypad.getKey();
if (key) {
// Handle keypad input
if (isdigit(key)) { // Check if pressed key is a digit (0-9)
if (enteredChars < codeLength) {
enteredCode[enteredChars++] = key;
lcd.setCursor(enteredChars, 0); // Move cursor to next digit position
lcd.print("*"); // Display asterisk for each entered digit (optional, for visual feedback)
}
} else if (key == '#') { // Handle enter key (#)
if (enteredChars == codeLength) {
if (strncmp(enteredCode, correctCode, codeLength) == 0) {
// Unlock door if code is correct
doorIsLocked = false;
lcd.clear();
lcd.print("Door Unlocked!");
} else {
// Display error message on incorrect code
lcd.clear();
lcd.print("Incorrect Code!");
delay(2000);
lcd.clear();
enteredChars = 0; // Reset entered code for next attempt
}
} else {
// Display message for incomplete code entry
lcd.clear();
lcd.print("Enter Full Code!");
delay(2000);
lcd.clear();
enteredChars = 0; // Reset entered code for next attempt
}
} else {
// Handle invalid key presses (optional: display message or ignore)
}
}
updateDoorStatus(); // Update LCD even without keypad input
delay(250); // Delay to avoid rapid key reading issues
}
void updateDoorStatus() {
lcd.setCursor(5, 0);
if (doorIsOpen) {
lcd.print("Open");
} else {
lcd.print("Closed");
}
lcd.setCursor(0, 1);
lcd.print("Lock: ");
if (doorIsLocked) {
lcd.print("Locked");
} else {
lcd.print("Unlocked");
}
}