#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 17, 16, 4, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 23, 19, 18, 5 }; // Pins connected to R1, R2, R3, R4
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal_I2C lcd(0x27, 16, 2);
int count = 0;
int a = 0, b = 0, c = 0, d = 0;
int var = 0;
int C1 = 1, C2 = 2, C3 = 3, C4 = 4;
bool success = false;
bool buzzerEnabled = false; // Menyimpan status apakah buzzer diizinkan atau tidak
int wrongAttempts = 0; // Menghitung jumlah kesalahan password
void setup() {
pinMode(12, OUTPUT); // Pin for door lock
pinMode(27, OUTPUT); // Pin for buzzer
lcd.init();
lcd.backlight();
Serial.begin(115200);
Serial.println("Hello, ESP32!");
}
void loop() {
char key = keypad.getKey();
if (success) {
if (key == 'A') {
success = false;
lcd.setCursor(3, 1);
lcd.print("door lock");
delay(1000);
digitalWrite(12, LOW); // Turn off pin 12
lcd.clear();
}
return; // Exit the loop early to prevent further processing of the key
}
if (key) {
lcd.setCursor(6 + var, 1);
lcd.print(key);
key = key - 48;
var++;
switch (var) {
case 1:
a = key;
break;
case 2:
b = key;
break;
case 3:
c = key;
break;
case 4:
d = key;
delay(50);
if (a == C1 && b == C2 && c == C3 && d == C4) {
lcd.clear();
lcd.setCursor(4, 0);
count = 0;
wrongAttempts = 0; // Reset wrong attempts on successful entry
digitalWrite(12, HIGH);
lcd.print("SUCCESS");
success = true;
} else {
// Menambah jumlah kesalahan password
wrongAttempts++;
// Mengatur bunyi buzzer berdasarkan jumlah kesalahan password
if (wrongAttempts == 1) {
// Jika jumlah kesalahan password pertama kali, tidak ada bunyi buzzer
buzzerEnabled = false;
} else if (wrongAttempts == 3) {
// Jika jumlah kesalahan password ketiga kali, aktifkan bunyi buzzer
buzzerEnabled = true;
}
if (buzzerEnabled) {
// Aktifkan bunyi buzzer jika diizinkan
tone(27, 1000, 500); // Generate a 1kHz tone for 500ms on pin 27
}
if (count == 2) {
digitalWrite(12, LOW);
delay(200);
}
lcd.clear();
lcd.setCursor(4, 0);
lcd.print("DENIED");
delay(1000);
lcd.clear();
count++;
}
// Reset count and wrongAttempts if count reaches 4
if (count == 4) {
count = 0;
wrongAttempts = 0;
}
var = 0;
break;
}
}
if (!key && !success) {
lcd.setCursor(0, 0);
lcd.print("Enter Password");
}
delay(2);
}