#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
#define ROW_NUM     4 // four rows
#define COLUMN_NUM  4 // four columns
LiquidCrystal_I2C lcd= LiquidCrystal_I2C(0x27,16,2);

#define SERVO_PIN 2 // ESP32 pin GPIO26 connected to servo motor

Servo servoMotor;

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]      = {33, 25, 26, 14}; // GPIO19, GPIO18, GPIO5, GPIO17 connect to the row pins
byte pin_column[COLUMN_NUM] = {27, 13, 18, 4};
Keypad keypad = Keypad( makeKeymap(keys), pin_rows, pin_column, ROW_NUM, COLUMN_NUM );
String input_password;
String password="29052002";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  Serial.println("Hello, ESP32!");

  Serial.begin(115200);
  
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.println("enter your password:");

  servoMotor.attach(SERVO_PIN);
  lock();
}
void unlock(){
  for (int pos = 90; pos >=0; pos -= 1) {
    // in steps of 1 degree
    servoMotor.write(pos);
    delay(15); // waits 15ms to reach the position
  }
}
void lock(){
  for (int pos = 0; pos <= 90; pos += 1) {
    servoMotor.write(pos);
    delay(15); // waits 15ms to reach the position
  }
}
void loop() {
  char key = keypad.getKey();
  if (key) {
    Serial.println(key);
    if(key=='D'){
       lcd.setCursor(0,1);
        lcd.println("                         ");
    }else{
    if (key == '*') {
      input_password = ""; // clear input password
    } else if (key == '#') {
      if (password == input_password) {
        lcd.setCursor(0,1);
        lcd.println("unlock");
        unlock();
      } else {
        lcd.setCursor(0,0);
        lcd.println("                         ");
        lcd.setCursor(0,1);
        lcd.println("incorrect");
        delay(1000);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.println("enter your password:");
      }

      input_password = ""; // clear input password
    } else {
        input_password += key;
        lcd.setCursor(0,1);
        lcd.println(input_password);
      // append new character to input password string
    }
  }
  }
  delay(10); // this speeds up the simulation
}
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
keypad1:R1
keypad1:R2
keypad1:R3
keypad1:R4
keypad1:C1
keypad1:C2
keypad1:C3
keypad1:C4
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL
servo1:GND
servo1:V+
servo1:PWM