#include <Keypad.h>
#include <LiquidCrystal.h>
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] = {9, 8, 7, 6}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3, 2}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // RS, EN, D4, D5, D6, D7
const int ledPin = 13;
const int buzzerPin = 10;
const char correctPasscode[] = "1234"; // Change this to your desired initial passcode
char enteredPasscode[5]; // To store entered passcode
int passcodeIndex = 0;
bool locked = false;
int attempts = 3; // Maximum number of attempts
void setup() {
lcd.begin(16, 2);
lcd.print("Enter passcode:");
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
if (!locked) {
char key = keypad.getKey();
if (key != NO_KEY && passcodeIndex < 4) {
enteredPasscode[passcodeIndex++] = key;
lcd.setCursor(passcodeIndex - 1, 1);
lcd.print('*');
}
if (passcodeIndex == 4) {
enteredPasscode[4] = '\0'; // Null-terminate the entered passcode
delay(500); // Small delay for stability
if (strcmp(enteredPasscode, correctPasscode) == 0) {
lcd.clear();
lcd.print("Code correct");
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 1000, 1000); // Buzz for 1 second
delay(3000); // Keep the door open for 3 seconds
digitalWrite(ledPin, LOW);
passcodeIndex = 0; // Reset passcode index for the next attempt
attempts = 3; // Reset attempts after correct code entry
} else {
lcd.clear();
lcd.print("Code incorrect");
digitalWrite(ledPin, LOW);
for (int i = 0; i < 3; i++) {
tone(buzzerPin, 2000, 200); // Buzz at 2000 Hz for 0.2 second (repeated 3 times)
delay(300);
}
attempts--;
if (attempts == 0) {
lcd.setCursor(0, 1);
lcd.print("System locked");
locked = true;
delay(5000); // Lock for 5 seconds before allowing new attempts
lcd.clear();
lcd.print("Enter passcode:");
attempts = 3; // Reset attempts after unlocking
} else {
lcd.setCursor(0, 1);
lcd.print("Attempts left: ");
lcd.print(attempts);
}
}
delay(2000); // Wait for 2 seconds before resetting
lcd.clear();
lcd.print("Enter passcode:");
passcodeIndex = 0;
memset(enteredPasscode, 0, sizeof(enteredPasscode)); // Reset the entered passcode
}
}
}