#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include<EEPROM.h>
#define servoPin 6
#define tombol 11
LiquidCrystal_I2C lcd(0X27, 16, 2);
char password[4] ,pass[4] , pass1[4];
int i = 0;
char customKey = 0;
const byte ROWS = 4, COLS = 4;
char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}, colPins[COLS] = {A3, A2, A1, A0}; 
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup()
{
  pinMode(servoPin, OUTPUT);
  pinMode(tombol, INPUT);
  lcd.init();
  lcd.backlight();
  lcd.print(" SELAMAT DATANG ");
  lcd.setCursor(4, 1);
  lcd.print(" *^__^* ");
  delay(1000);
  lcd.clear();
  lcd.print("Masukkan Kode :");
  lcd.setCursor(0, 1);
  for (int j = 0; j < 4; j++)
    EEPROM.write(j, j + 49);
  for (int j = 0; j < 4; j++)
    pass[j] = EEPROM.read(j);
  tutup();
}//UNTUNG BUDI UTOMO_D400200062
void loop()
{
  int dalam =digitalRead(tombol);
  customKey = customKeypad.getKey();
  if (customKey == '#')
    change();
  if (customKey)
  {
    password[i++] = customKey;
    lcd.print(customKey);
  }
  if (i == 4)
  {
    delay(200);
    for (int j = 0; j < 4; j++)
      pass[j] = EEPROM.read(j);
    if (!(strncmp(password, pass, 4)))
    {
      buka();
      lcd.clear();
      lcd.print("   Kode Benar");
      delay(2000);
      lcd.setCursor(0, 1);
      lcd.print("#. Ubah Kode");
      delay(2000);
      lcd.clear();
      lcd.print("Masukkan Kode:");
      lcd.setCursor(0, 1);
      i = 0;
      tutup();
    }
    else
    {
      tutup();
      lcd.clear();
      lcd.print("    Kode Salah");
      lcd.setCursor(0, 1);
      lcd.print("#. Ubah Kode");
      delay(2000);
      lcd.clear();
      lcd.print("Masukkan Kode :");
      lcd.setCursor(0, 1);
      i = 0;
    }
  }
  if (dalam == HIGH){
    buka();
    delay(2000);
    tutup();
  }
  }
void change()
{
  int j = 0;
  lcd.clear();
  lcd.print("Kode Sekarang :");
  lcd.setCursor(0, 1);
  while (j < 4)
  {
    char key = customKeypad.getKey();
    if (key)
    {
      pass1[j++] = key;
      lcd.print(key);
    }
    key = 0;
  }
  delay(500);
  if ((strncmp(pass1, pass, 4)))
  {
    lcd.clear();
    lcd.print("   Kode Salah..");
    delay(1000);
  }
  else
  {
    j = 0;
    lcd.clear();
    lcd.print("Kode baru :");
    lcd.setCursor(0, 1);
    while (j < 4)
    {
      char key = customKeypad.getKey();
      if (key)
      {
        pass[j] = key;
        lcd.print(key);
        EEPROM.write(j, key);
        j++;
      }
    }
    lcd.print(" Done......");
    delay(1000);
  }
  lcd.clear();
  lcd.print("Masukkan Kode:");
  lcd.setCursor(0, 1);
  customKey = 0;
}
void tutup(){
  digitalWrite(servoPin, HIGH);
  delayMicroseconds(1450); 
  digitalWrite(servoPin, LOW);
  delayMicroseconds(18550);
}
void buka(){
  digitalWrite(servoPin, HIGH);
  delayMicroseconds(600); 
  digitalWrite(servoPin, LOW);
  delayMicroseconds(18550);
}