#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
// LCD pin connections: RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Keypad setup
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] = {A3, A2, A1, A0}; // R1, R2, R3, R4
byte colPins[COLS] = {6, 5, 4, 3}; // C1, C2, C3, C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Pins
const int greenLED = 2;
const int redLED = A4;
const int buzzer = A5;
const int trigPin = 1; // HC-SR04 Trig
const int echoPin = 0; // HC-SR04 Echo
Servo myServo;
// Password
String password = "1234";
String input = "";
String lastMessage = ""; // Stores last message to prevent blinking
void setup() {
lcd.begin(16, 2);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(13);
myServo.write(0); // start locked
lcd.setCursor(0, 0);
lcd.print("System Ready");
lastMessage = "System Ready";
}
void loop() {
long duration;
int distance;
// Ultrasonic sensor reading
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Show message only when it changes
if (distance > 30) {
if (lastMessage != "No one nearby") {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("No one nearby");
lastMessage = "No one nearby";
}
}
else {
if (lastMessage != "Enter Password") {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
lastMessage = "Enter Password";
}
handleKeypad();
}
}
void handleKeypad() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
checkPassword();
input = "";
delay(1500);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
lastMessage = "Enter Password";
}
else if (key == '*') {
input = "";
lcd.setCursor(0, 1);
lcd.print(" "); // Clear second line
}
else if (input.length() < 4) {
input += key;
lcd.setCursor(input.length() - 1, 1);
lcd.print("*");
}
}
}
void checkPassword() {
lcd.clear();
if (input == password) {
lcd.setCursor(0, 0);
lcd.print("Access Granted!");
digitalWrite(greenLED, HIGH);
myServo.write(90); // Unlock
delay(3000);
myServo.write(0); // Lock
digitalWrite(greenLED, LOW);
} else {
lcd.setCursor(0, 0);
lcd.print("Wrong Password!");
for (int i = 0; i < 3; i++) {
digitalWrite(redLED, HIGH);
tone(buzzer, 1000);
delay(300);
digitalWrite(redLED, LOW);
noTone(buzzer);
delay(300);
}
}
}