#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
Servo S;
#define buzz 11
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 3;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A1, A2, A3};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3',},
{'4', '5', '6',},
{'7', '8', '9',},
{'*', '0', '#',}
};
int led1= 13;
int led2= 12;

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

void Start() {
lcd.backlight();
lcd.setCursor(5, 1);
lcd.print("Welcome");
delay(1000);

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

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

void Unlocked() {
lcd.clear();
                                                   
lcd.setCursor(5, 1);            
lcd.print("Unlocked");
delay(1000);
}
void Lock() {
lcd.clear();
lcd.setCursor(5, 1);
lcd.print("Locked");
delay(1000);
}

void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
Start();
S.attach(6);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(buzz, OUTPUT);
}


void loop() {


if(inputSecretCode()=="1234")
{
Unlocked(); 
digitalWrite(led2, HIGH);
delay(500);
digitalWrite(led2, LOW);
delay(500);
S.write(180);
                                                
for (int i = 0; i < 10; i++){
tone(buzz, 800, 150);
delay(20);
}
}
else
{
Lock();
digitalWrite(led1, HIGH);
delay(500);                                                                                
digitalWrite(led1, LOW);                                                                                                                              
delay(500);
S.write(90);

for (int i = 0; i < 10; i++){
tone(buzz, 200, 150);
delay(50);
}
}
}