#include <LiquidCrystal.h>
#include <Keypad.h>
// LCD pins: RS=7, E=8, D4=9, D5=10, D6=11, D7=12
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
// Ultrasonic sensor pins
#define TRIG_PIN 2
#define ECHO_PIN 13
// Output devices
#define BUZZER_PIN 1
#define LED_PIN 0
// Password and user input
String password = "2580";
String input = "";
int attempts = 3;
// Keypad config
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] = {6, 5, 4, 3}; // R1 to R4
byte colPins[COLS] = {A0, A1, A2, A3}; // C1 to C4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
lcd.begin(16, 2);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
lcd.print("Smart Security");
delay(2000);
lcd.clear();
}
void loop() {
long duration, distance;
// Trigger ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2;
if (distance < 100) {
lcd.clear();
lcd.print("Welcome Home!");
delay(1500);
lcd.clear();
lcd.print("Enter PIN:");
lcd.setCursor(0, 1);
input = "";
while (attempts > 0) {
char key = keypad.getKey();
if (key && isDigit(key)) {
input += key;
lcd.print("*");
if (input.length() == 4) {
if (input == password) {
lcd.clear();
lcd.print("Access Granted");
digitalWrite(LED_PIN, HIGH); // open door
delay(5000);
digitalWrite(LED_PIN, LOW);
lcd.clear();
lcd.print("Welcome!");
delay(2000);
break;
} else {
attempts--;
lcd.clear();
if (attempts > 0) {
lcd.print("Wrong PIN");
lcd.setCursor(0, 1);
lcd.print("Chances: ");
lcd.print(attempts);
delay(2000);
lcd.clear();
lcd.print("Enter PIN:");
lcd.setCursor(0, 1);
input = "";
} else {
lcd.print("INTRUDER!");
digitalWrite(BUZZER_PIN, HIGH);
delay(5000);
digitalWrite(BUZZER_PIN, LOW);
while (1); // lock system
}
}
}
}
}
attempts = 3; // Reset for next person
lcd.clear();
lcd.print("System Ready");
delay(2000);
lcd.clear();
}
}