#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
// Initialize LCD with I2C address (Check with I2C scanner: usually 0x27 or 0x3F)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Keypad configuration
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] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define Components
Servo doorLock;
#define BUZZER 11
#define RED_LED 12
#define GREEN_LED 13
// Set a fixed PIN for unlocking the door
String password = "1234"; // Change this to your desired password
String inputPassword = "";
void setup() {
Serial.begin(9600);
lcd.begin(16, 2); // Initialize LCD
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Smart Door Lock");
pinMode(BUZZER, OUTPUT);
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
doorLock.attach(10);
doorLock.write(0); // Locked position
}
void loop() {
lcd.setCursor(0, 1);
lcd.print("Enter PIN: ");
char key = keypad.getKey();
if (key) {
Serial.print(key);
if (key == '*') {
inputPassword = ""; // Clear input on '*'
lcd.setCursor(0, 1);
lcd.print("Enter PIN: "); // Clear previous input
}
else if (key == '#') {
checkPassword(); // Validate input
}
else {
inputPassword += key;
lcd.setCursor(10, 1);
lcd.print(inputPassword);
}
}
}
void checkPassword() {
lcd.setCursor(0, 1);
lcd.print("Checking... ");
delay(1000);
if (inputPassword == password) {
unlockDoor();
}
else {
lcd.setCursor(0, 1);
lcd.print("Access Denied! ");
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
tone(BUZZER, 1000, 500); // Buzzer alert
delay(2000);
}
inputPassword = ""; // Reset password input
lcd.setCursor(0, 1);
lcd.print("Enter PIN: ");
}
void unlockDoor() {
lcd.setCursor(0, 1);
lcd.print("Access Granted!");
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
tone(BUZZER, 500, 300);
doorLock.write(90); // Unlock position
delay(5000); // Keep door open for 5 seconds
doorLock.write(0); // Lock position
lcd.setCursor(0, 1);
lcd.print("Enter PIN: ");
}