#include <Keypad.h>
#include <EEPROM.h>
#include <ESP32Servo.h>
const int BARIS = 4;
const int KOLOM = 4;
char keys[BARIS][KOLOM] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[BARIS] = {22, 21, 19, 18}; // Hubungkan ke pin baris keypad
byte colPins[KOLOM] = {5, 4, 2, 15}; // Hubungkan ke pin kolom keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, BARIS, KOLOM);
Servo doorLock;
int unlockedPosition = 90;
int lockedPosition = 0;
boolean isLocked = true;
String correctPIN; // Kode PIN yang benar
void setup() {
Serial.begin(9600);
doorLock.attach(26); // Hubungkan servo ke pin GPIO 26
EEPROM.begin(512);
loadPINFromEEPROM();
lockDoor();
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
Serial.print(key); // Menampilkan karakter PIN yang dimasukkan
if (key == '#') {
// Tombol "#" ditekan, periksa kode PIN
if (isLocked) {
// Pintu terkunci, minta kode PIN
String enteredPIN = "";
while (key != '*') {
key = keypad.getKey();
if (key != NO_KEY) {
enteredPIN += key;
}
}
if (enteredPIN == correctPIN) {
unlockDoor();
Serial.println("\nPIN benar. Pintu terbuka.");
} else {
// Kode PIN salah, kunci pintu kembali
lockDoor();
Serial.println("\nPIN salah. Pintu terkunci.");
}
// Tampilkan PIN yang dimasukkan pada Serial Monitor
Serial.print("PIN yang dimasukkan: ");
Serial.println(enteredPIN);
} else {
// Pintu sudah terbuka, kunci kembali
lockDoor();
}
}
if (key == 'A') {
// Tombol "A" ditekan, memulai proses penggantian PIN
Serial.println("\nMasukkan PIN baru:");
String newPIN = "";
while (newPIN.length() < 6) {
key = keypad.getKey();
if (key != NO_KEY) {
newPIN += key;
Serial.print(key); // Menampilkan karakter PIN baru yang dimasukkan
}
}
correctPIN = newPIN;
savePINToEEPROM();
Serial.println("\nPIN baru telah disimpan: " + correctPIN);
}
}
}
void lockDoor() {
doorLock.write(lockedPosition);
isLocked = true;
Serial.println("Pintu terkunci");
}
void unlockDoor() {
doorLock.write(unlockedPosition);
isLocked = false;
Serial.println("Pintu terbuka");
}
void loadPINFromEEPROM() {
correctPIN = "";
for (int i = 0; i < 6; i++) {
correctPIN += char(EEPROM.read(i));
}
}
void savePINToEEPROM() {
for (int i = 0; i < 6; i++) {
EEPROM.write(i, correctPIN[i]);
}
EEPROM.commit();
}