#include <LiquidCrystal.h>
#include <Keypad.h>
#include <Servo.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
Servo S;
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A0, A1, A2, A3};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
int l1= 13;

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS, KEYPAD_COLS);

void showStartupMessage() {
  lcd.setCursor(4, 0);
  lcd.print("Welcome!");
  delay(1000);

  lcd.setCursor(0, 2);
  String message = "Input PIN";
  for (byte i = 0; i < message.length(); i++) {
    lcd.print(message[i]);
    delay(100);
  }
  delay(500);
}

String inputSecretCode() {
  lcd.clear();
  lcd.setCursor(5, 1);
  lcd.print("[____]");
  lcd.setCursor(6, 1);
  String result = "";
  while (result.length() < 4) {
    char key = keypad.getKey();
    if (key >= '0' && key <= '9') {
      lcd.print('*');
      result += key;
    }
  }
  return result;
}

void showUnlockMessage() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Unlocked!");
  delay(1000);
}
void showLockMessage() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("Locked!");
  delay(1000);
}


void setup() {
  lcd.begin(16, 2);
  showStartupMessage();
  S.attach(6);
  pinMode(l1, OUTPUT);
}

void loop() {
 if(inputSecretCode()=="1234")
 {
  showUnlockMessage(); 
  S.write(180);
  delay(1000);
  S.write(90);
 }
 else
 {
   showLockMessage();
   digitalWrite(l1, HIGH);
   delay(1000);
   digitalWrite(l1, LOW);
}
}