#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// LCD setup
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust address if needed
// Keypad setup
char keys[4][4] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[4] = {2, 3, 4, 5}; // Keypad rows to GPIO pins
byte colPins[4] = {A0, A1, A2, A3}; // Keypad columns to GPIO pins
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 4);
// Relay setup (LED is connected to the relay pin)
int relayPin = 8; // GPIO pin connected to relay (ensure no conflict)
// Password settings
String storedPassword = "4647"; // Default password
String enteredPassword = ""; // User-entered password
int maxPasswordLength = 4; // Maximum password length
// Initialization
bool locked = true; // System is locked by default
void setup() {
// Initialize LCD
lcd.begin(16, 2);
lcd.backlight();
lcd.clear();
// Display welcome message
lcd.print("Welcome to");
lcd.setCursor(0, 1);
lcd.print("Field Work");
delay(3000); // Display for 3 seconds
lcd.clear();
// Initialize relay
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // Relay off initially
// Display initialization message
lcd.print("System Locked");
delay(2000);
lcd.clear();
lcd.print("Enter Password:");
}
void loop() {
char key = keypad.getKey(); // Get pressed key
if (key) {
handleKeyPress(key); // Handle key press
}
}
void handleKeyPress(char key) {
if (key == '*') { // Reset on '*' key
resetSystem(); // Reset password entry
digitalWrite(relayPin, LOW); // Turn OFF relay (LED off)
} else if (key == '#') { // Validate password on '#' key
validatePassword();
} else { // Append key to entered password
if (enteredPassword.length() < maxPasswordLength) {
enteredPassword += key;
displayPassword();
}
}
}
void validatePassword() {
lcd.clear();
if (enteredPassword == storedPassword) {
// Correct password
lcd.print("ACCESS GRANTED");
digitalWrite(relayPin, HIGH); // Turn ON relay (LED on)
locked = false;
lcd.setCursor(0, 1);
lcd.print("Circuit ON");
// No resetSystem() here to keep the message on screen
} else {
// Incorrect password
lcd.print("WRONG PASSWORD");
locked = true;
digitalWrite(relayPin, LOW); // Keep relay OFF (LED off)
lcd.setCursor(0, 1);
lcd.print("Try Again");
delay(2000);
resetSystem();
}
}
void resetSystem() {
enteredPassword = ""; // Clear entered password
lcd.clear();
lcd.print("Enter Password:");
}
void displayPassword() {
lcd.setCursor(0, 1);
lcd.print(" "); // Clear second row
lcd.setCursor(0, 1);
lcd.print(enteredPassword); // Display the entered password
}