#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Four columns
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}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int relayPin = 13; // Connect the relay to pin 13
// Define passcode
const char passcode[] = "0704"; // Change this to your desired passcode
char enteredCode[5]; // Buffer to store entered code
// Initialize the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); // Set the LCD I2C address to 0x27, 16 characters and 2 lines
void setup()
{
pinMode(relayPin, OUTPUT); // Set the relay pin as output
Serial.begin(9600); // Initialize serial communication for debugging
// Initialize LCD
lcd.init();
lcd.backlight();
Serial.println("Enter Passcode:");
lcd.print("Enter Passcode:");
lcd.setCursor(0, 1); // Set cursor to the first column of the second row
}
void loop()
{
char key = keypad.getKey();
if (key)
{
if (key == '#') // If # key is pressed, check the passcode
{
if (strlen(enteredCode) == 4) // Check if passcode length is 4
{
enteredCode[4] = '\0'; // Null terminate the string
if (strcmp(enteredCode, passcode) == 0) // If the entered passcode matches the stored passcode, activate the relay
{
digitalWrite(relayPin, HIGH);
lcd.clear();
Serial.println("\nAccess Granted");
lcd.print("Access Granted");
delay(20000); // Delay to keep the relay activated for a short duration
digitalWrite(relayPin, LOW); // Deactivate the relay after delay
lcd.clear();
}
else
{
lcd.clear();
Serial.println("\nAccess Denied");
lcd.print("Access Denied");
}
memset(enteredCode, 0, sizeof(enteredCode)); // Clear the entered code buffer
}
else
{
lcd.clear();
Serial.println("\nInvalid Passcode");
lcd.print("Invalid Passcode");
memset(enteredCode, 0, sizeof(enteredCode)); // Clear the entered code buffer
}
delay(1000);
lcd.clear();
Serial.println("\nEnter Passcode:");
lcd.print("Enter Passcode:"); // Display prompt for next passcode entry
lcd.setCursor(0, 1); // Set cursor to the first column of the second row
}
else if (strlen(enteredCode) < 4) // If less than 4 digits have been entered
{
enteredCode[strlen(enteredCode)] = key; // Store the pressed key
Serial.print(key);
lcd.print(key); // Print the pressed key on LCD
}
}
}