#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Keypad settings
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t rowPins[ROWS] = { 18, 5, 17, 16 }; // Pins connected to R1, R2, R3, R4
uint8_t colPins[COLS] = { 4, 0, 2, 15 }; // Pins connected to C1, C2, C3, C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// LCD settings
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change the I2C address (0x27) if needed
// Relay settings
const int relayPin = 19; // Pin connected to the relay module
// Password settings
String storedPassword = ""; // Password storage
String inputPassword = ""; // Password input
bool settingPassword = true; // Flag to set password
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
// I2C scanner
Serial.println("Scanning I2C bus...");
Wire.begin();
for (uint8_t address = 1; address < 127; address++) {
Wire.beginTransmission(address);
if (Wire.endTransmission() == 0) {
Serial.print("I2C device found at address 0x");
if (address < 16) Serial.print("0");
Serial.println(address, HEX);
}
}
Serial.println("Scan complete.");
// Initialize LCD
lcd.begin(16, 2); // initialize the lcd
lcd.backlight(); // turn on the backlight
lcd.clear();
lcd.print("Set Password:");
lcd.setCursor(0, 1); // Move the cursor to the second line
// Initialize relay pin
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // Initial state: relay off
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
Serial.println(key);
if (key == '#') {
// End of password entry
if (settingPassword) {
storedPassword = inputPassword;
inputPassword = "";
settingPassword = false;
lcd.clear();
lcd.print("Enter Password:");
lcd.setCursor(0, 1);
} else {
if (inputPassword == storedPassword) {
lcd.clear();
lcd.print("Access Granted");
digitalWrite(relayPin, HIGH); // Turn on the relay
delay(5000); // Keep it on for 5 seconds
digitalWrite(relayPin, LOW); // Turn off the relay
lcd.clear();
lcd.print("Enter Password:");
} else {
lcd.clear();
lcd.print("Access Denied");
delay(2000); // Wait for 2 seconds
lcd.clear();
lcd.print("Enter Password:");
}
inputPassword = "";
lcd.setCursor(0, 1);
}
} else if (key == '*') {
// Clear the input password
inputPassword = "";
lcd.clear();
if (settingPassword) {
lcd.print("Set Password:");
} else {
lcd.print("Enter Password:");
}
lcd.setCursor(0, 1);
} else {
// Append the key to the input password
inputPassword += key;
lcd.print('*'); // Print asterisk for each character entered
}
}
}