#include <Servo.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#define PIN_TRIG 9
#define PIN_ECHO 12
#define redLED 10
#define greenLED 13
#define timeDelay 5000
const uint8_t ROWS = 4;
const uint8_t COLS = 3;
char keys[ROWS][COLS] = {
{ '1', '2', '3',},
{ '4', '5', '6',},
{ '7', '8', '9',},
{ '*', '0', '#',}
};
uint8_t rowPins[ROWS] = { 8, 7, 6, 5 }; // Pins connected to R1, R2, R3, R4
uint8_t colPins[COLS] = { 4, 3, 2 }; // Pins connected to C1, C2, C3
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 20, 4);
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String password = "7777";
String enterPass = "";
bool passEntered;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
myservo.attach(11);
lcd.init();
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
int duration = pulseIn(PIN_ECHO, HIGH);
int distance = duration / 58;
if(distance < 150) { // Sensor activated
char key = keypad.getKey();
lcd.backlight();
if (passEntered == false) { // Input password
lcd.setCursor(1, 1);
lcd.print("ENTER PASSWORD :");
passEntered = true;
}
if (key != NO_KEY) {
if (key == '#') {
if (password == enterPass) { // Password correct
beep();
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, LOW);
myservo.write(0);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("PASSWORD CORRECT");
lcd.setCursor(1, 1);
lcd.print("DOOR OPENED");
delay(timeDelay);
lcd.clear();
reset();
}
else { // Password incorrect
digitalWrite(greenLED, LOW);
digitalWrite(redLED, HIGH);
myservo.write(90);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("PASSWORD INCORRECT");
reset();
}
}
else { // Input password
enterPass += key;
lcd.setCursor(1, 3);
lcd.print(enterPass);
}
}
} else { // Sensor inactive
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
myservo.write(90);
lcd.clear();
lcd.noBacklight();
reset();
}
}
void beep() {
tone(8, 1000, 50);
}
void reset() {
passEntered = false;
enterPass = "";
}