/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-keypad-solenoid-lock
*/
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#define RELAY_PIN 5 // ESP32 pin GPIO19 connected to the relay
#define ROW_NUM 4 // keypad four rows
#define COLUMN_NUM 4 // keypad three 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] = {12, 14, 27, 26}; // ESP32 pin: GPIO12, GPIO14, GPIO27, GPIO26 connected to the row pins
byte pin_column[COLUMN_NUM] = {25, 33, 13, 32}; // ESP32 pin: GPIO25, GPIO33, GPIO32 connected to the column pins
Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27 (from DIYables LCD), 16 column and 2 rows
int cursorColumn = 0;
const String password_1 = "1234"; // change your password here
String input_password;
void setup() {
Serial.begin(9600);
input_password.reserve(32); // maximum password size is 32, change if needed
pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output.
digitalWrite(RELAY_PIN, LOW); // lock the solenoid lock
lcd.init(); // initialize the lcd
lcd.backlight();
}
void loop() {
lcd.setCursor(0, 0); // move cursor to (cursorColumn, 0)
lcd.print("Enter the OTP");
char key = keypad.getKey();
if (key) {
lcd.setCursor(cursorColumn, 1);
lcd.print(key);
cursorColumn++;
Serial.println(key);
if (key == '*') {
input_password = ""; // reset the input password
lcd.clear();
cursorColumn=0;
} else if (key == '#') {
if (input_password == password_1) {
Serial.println("The password is correct => unlock");
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("Correct Password");
delay(2000);
lcd.clear();
digitalWrite(RELAY_PIN, HIGH);
delay(4000);
digitalWrite(RELAY_PIN, LOW);
} else {
Serial.println("The password is incorrect, try again");
lcd.clear();
lcd.setCursor(0, 1);
lcd.print("InCorrect Password");
delay(2000);
lcd.clear();
}
cursorColumn=0;
input_password = ""; // reset the input password
}
else {
input_password += key; // append new character to input password string
}
}
}