#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <ESP32Servo.h>
// Initialize LCD (I2C address 0x27)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Initialize servo
Servo myservo;
// Define keypad size
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] = {23, 22, 21, 19}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {18, 17, 16, 4}; // connect to the column pinouts of the keypad
// Create the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Define pins
#define BUZZER_PIN 27
#define SERVO_PIN 32
#define RED_LED_PIN 12
#define GREEN_LED_PIN 14
// Variables
String password = "";
String input_password = "";
bool password_set = false;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize LCD
lcd.begin(16, 2);
lcd.backlight();
// Initialize pins
pinMode(BUZZER_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
// Attach the servo
myservo.attach(SERVO_PIN);
// Initial state
myservo.write(0); // Lock position
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
// Prompt to set the password
lcd.setCursor(0, 0);
lcd.print("Set Password:");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (!password_set) {
if (key == '#') {
password_set = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
} else {
password += key;
lcd.setCursor(password.length() - 1, 1);
lcd.print("*");
}
} else {
if (key == '#') {
if (input_password == password) {
// Correct password
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Access Granted");
myservo.write(90); // Open position
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
delay(5000); // Keep open for 5 seconds
myservo.write(0); // Lock position
digitalWrite(GREEN_LED_PIN, LOW);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
} else {
// Incorrect password
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wrong Password");
digitalWrite(RED_LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
delay(2000); // Buzzer for 2 seconds
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW); // Turn off the red LED
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter Password:");
}
input_password = ""; // Reset input
} else {
input_password += key;
lcd.setCursor(input_password.length() - 1, 1);
lcd.print("*");
}
}
}
}