#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
const int servoPin = 10; // Connect servo to digital pin 9
const int redLedPin = 11; // Connect red LED to digital pin 10
const int greenLedPin = 12; // Connect green LED to digital pin 11
const int buzzerPin = 13; // Connect buzzer to digital pin 12
Servo myServo;
const byte ROW_NUM = 4; // four rows
const byte COLUMN_NUM = 4; // four columns
char keys[ROW_NUM][COLUMN_NUM] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte pin_rows[ROW_NUM] = {2, 3, 4, 5}; // connect to the row pinouts of the keypad
byte pin_column[COLUMN_NUM] = {6, 7, 8, 9}; // connect to the column pinouts of the keypad
Keypad myKeypad = Keypad(makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM);
String enteredPassword = "";
String correctPassword = "1234"; // Change this to your desired password
int wrongAttempts = 0;
const int maxWrongAttempts = 3;
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows
void setup() {
myServo.attach(servoPin);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
myServo.write(90); // Lock the servo initially
lcd.begin(16, 2); // Initialize the LCD
lcd.print("Enter password:");
Serial.begin(9600);
}
void loop() {
char key = myKeypad.getKey();
if (key) {
if (key == '#') {
// Check the entered password when '#' is pressed
if (enteredPassword == correctPassword) {
lcd.clear();
lcd.print("Password correct");
lcd.setCursor(0, 1);
lcd.print("Unlocking...");
digitalWrite(greenLedPin, HIGH); // Turn on green LED
unlock();
} else {
lcd.clear();
lcd.print("Incorrect password");
lcd.setCursor(0, 1);
lcd.print("Locking...");
digitalWrite(redLedPin, HIGH); // Turn on red LED
lock();
wrongAttempts++;
// Buzz the buzzer if three wrong attempts are reached
if (wrongAttempts >= maxWrongAttempts) {
digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
delay(1000); // Buzz for 1 second
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
wrongAttempts = 0; // Reset the wrong attempts counter
}
}
// Clear entered password for the next attempt
enteredPassword = "";
// Delay to display the result on the LCD
delay(2000);
// Turn off LEDs and clear LCD
digitalWrite(redLedPin, LOW);
digitalWrite(greenLedPin, LOW);
lcd.clear();
lcd.print("Enter password:");
} else {
// Append the pressed key to the entered password
enteredPassword += key;
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the line
lcd.setCursor(0, 1);
lcd.print(enteredPassword);
}
}
}
void unlock() {
myServo.write(0); // Open the lock
delay(8000); // Keep the lock open for 8 seconds
myServo.write(90); // Close the lock
}
void lock() {
myServo.write(90); // Close the lock
delay(1000); // Keep the lock closed for 1 second
}