#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>

// กำหนดค่าหน้าจอ LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);

// กำหนดค่าคีย์แพด
const byte ROWS = 4; 
const byte COLS = 4; 
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

// กำหนดค่ามอเตอร์เซอร์โว
Servo myServo;
int servoPin = 10;
String password = "1234"; // กำหนดรหัสผ่าน
String inputPassword = "";

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Enter Password:");
  myServo.attach(servoPin);
  myServo.write(0); // ล็อคประตู
}

void loop() {
  char key = keypad.getKey();
  if (key) {
    lcd.setCursor(inputPassword.length(), 1);
    lcd.print("*");
    inputPassword += key;
    if (inputPassword.length() == 4) {
      delay(500);
      if (inputPassword == password) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Access Granted");
        myServo.write(90); // ปลดล็อคประตู
        delay(5000);
        myServo.write(0); // ล็อคประตูอีกครั้ง
      } else {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Access Denied");
        delay(2000);
      }
      inputPassword = "";
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Enter Password:");
    }
  }
}