#include <Wire.h>
#include <ESP32Servo.h> // Include the correct library
#include <LiquidCrystal.h>
#include <Keypad.h>
#define SERVO_PIN 14
#define SERVO_LOCK_POS 20 // position lock for servo motor
#define SERVO_UNLOCK_POS 90 // position unlock for servo motor
Servo lockServo;
String pad;
String enteredPassword; // Declare the variable
const byte numRows = 4;
const byte numCols = 4;
String password = "4321A";
char keypressed;
char keys[numRows][numCols] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[numRows] = {19, 18, 5, 17}; //connect to the row pinouts of the keypad
byte colPins[numCols] = {16, 4, 0, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, numRows, numCols);
LiquidCrystal lcd(19, 23, 18, 17, 16, 15); // RS, E, D4, D5, D6, D7
void setup() {
lcd.begin(16, 2); // Initialize the LCD
lcd.setCursor(0, 0);
lcd.print("Keypad");
lcd.setCursor(0, 1);
lcd.print("Test");
delay(1000);
lcd.clear();
servo.attach(servoPin); // Attach servo to pin
}
void loop() {
char key = keypad.getKey();
readKeypad();
if (keypressed == '#') {
if (pad == password) {
lcd.setCursor(0, 1);
lcd.print("Access Granted");
unlock();
} else {
lcd.setCursor(0, 1);
lcd.print("Access Denied");
}
if (keypressed == '*') {
pad = "";
lcd.clear();
}
lcd.setCursor(0, 0);
lcd.print(pad);
delay(100); // Add missing semicolon
} else {
// Concatenate the entered keys to form the password
enteredPassword += key;
// Display the entered password
lcd.setCursor(0, 1);
lcd.print(enteredPassword);
}
}
void readKeypad() {
keypressed = keypad.getKey(); //deteksi penekanan keypad
if (keypressed != '#') {
String konv = String(keypressed);
pad += konv;
}
}
void unlock() {
// Rotate the servo motor to open the lock
servo.write(90);
delay(2000); // Wait for 2 seconds (adjust as needed)
servo.write(0); // Return to the closed position
}