#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Keypad.h>
#include <ESP32Servo.h>
#include <classProcess.c>

#define TINGGI_LAYAR 64 // Tinggi layar OLED yang digunakan
#define LEBAR_LAYAR 128 // Lebar layar OLED yang digunakan

Servo myservo;
const byte ROWS = 4;    //Jumlah baris keypad
const byte COLS = 4;    //Jumlah kolom keypad

int buzzer = 25;

Adafruit_SSD1306 oled(LEBAR_LAYAR, TINGGI_LAYAR, &Wire, -1);

char Keys[ROWS][COLS] = {   //Membuat array keypad
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = { 14, 12, 19, 18 }; 
byte colPins[COLS] = { 5, 4, 2, 15 };

Keypad customKeypad = Keypad( makeKeymap(Keys), rowPins, colPins, ROWS, COLS);    //Masukkan info keypad pada library


char customKey;         //Variabel penampung input keypad
int number = 0;         //Variabel penampung nilai angka
int password = 1379;    //Password

void setup() {
  Serial.begin(9600);
  myservo.attach(26);
  pinMode(buzzer, OUTPUT);

  // initialize OLED display with I2C address 0x3C
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("failed to start SSD1306 OLED"));
    while (1);
  }
  oled.clearDisplay();
  
  setOled();
  oled.setCursor(20, 20);       // Atur posisi text pada display
  oled.println("SELAMAT DATANG"); // Text yang dicetak
  delay(2000);
  oled.display(); 
  oled.clearDisplay();// menampilkan display OLED
}

void setOled(){
  oled.clearDisplay();
  oled.setTextSize(1);
  oled.setTextColor(WHITE); 
  oled.setCursor(0,10);
}
void loop() {
  setOled();
  oled.print("Input Password");      //Tampilan pada layar LCD
  
  customKey = customKeypad.getKey(); 
  
  Serial.println(customKey);
  if (customKey=='*'){
      oled.clearDisplay();
  
  }
 
  //------------Prosedur jika input berupa angka------------//
  switch(customKey){
    case '0' ... '9':
      setOled(); 
      oled.setCursor(0,10);
      number = number * 10 + (customKey - '0');
      oled.print(number);
      oled.display();
       
    break;
//------------Jika input '*' maka hapus tampilan------------//
    
    //------------Jika input '#' maka cek password------------//
    case '#':
      if(number == password){          //Jika password benar, maka
        setOled();
        oled.print("Access Accepted ");  //Tampilan LCD
        number = 0;
        myservo.write(180);
        delay(5000);
        myservo.write(90);
        oled.display();
        
      }
      else{                             //Jika salah, maka
        setOled();
        oled.print("Invalid Password");  //Tampilan LCD
        oled.display();
        oled.clearDisplay();
        digitalWrite(buzzer, HIGH);
        delay(2000);
        number = 0;
      }
    break;
  }
}