#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define Buzz 12
#define LedPin 13
const byte ROWS = 4, 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 );

LiquidCrystal_I2C lcd(0x27, 16, 2);  

Servo myservo;
int pos = 0;

String password1 = "2222"; 
String password2 = "5555";
String password3 = "8888";

String inputPassword;

void setup(){
  lcd.init(); 
  lcd.backlight();
  myservo.attach(A0);
  pinMode(LedPin, OUTPUT); 
  pinMode(Buzz, OUTPUT); 
}
  
void loop(){
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Password 1:");
  inputPassword = getPassword();  
  if(inputPassword == password1){
    showPassword2(); 
  } else {
    accessDenied();  
  }
}

String getPassword(){
  
  String password = "";
  
  while(password.length() < 4){
    char key = keypad.getKey();
    if(key){
      password += key;
      lcd.print(key);
    }
  }

  return password;  
}

void showPassword2(){
  lcd.clear();
  lcd.print("Password 2:");
  
  inputPassword = getPassword();
  if(inputPassword == password2){
     showPassword3();
  } else {
     accessDenied();
  }  
}

void showPassword3(){
  lcd.clear();
  lcd.print("Password 3:");
  inputPassword = getPassword();
  if(inputPassword == password3){     
      digitalWrite(Buzz, HIGH);
  for (pos = 0; pos <= 180; pos += 10) { 
    myservo.write(pos); 
    delay(15);                       
    }
  for (pos = 180; pos >= 0; pos -= 10) { 
    myservo.write(pos);             
    delay(15);                       
     }
  } 
  else {
     accessDenied();
  }  
}

void accessDenied(){
  lcd.clear();
  lcd.print("Password Salah");
  digitalWrite(LedPin, HIGH);
  delay(1000);
  digitalWrite(LedPin, LOW); 
  lcd.clear();
}