//Nama    : Rizqi Fahmi Ilmi
//NIM     : 52004110023
//Prodi   : Informatika/8C
//Matkul  : Proyek Teknologi Informasi

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const byte ROWS = 4; //jumlah baris keypad
const byte COLS = 4; //jumlah kolom keypad

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

byte rowPins[ROWS] = {14, 12, 19, 18}; //R1, R2, R3, R4
byte colPins[COLS] = {5, 4, 2, 15}; //C1, C2, C3, C4

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

const char *password = "1234";
char enteredPassword[5];
int passwordIndex = 0;

const int greenLedPin = 26; // Lampu hijau
const int redLedPin = 27;   // Lampu merah

void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  pinMode(greenLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  lcd.setCursor(0, 0);
  lcd.print("Input Password:");
}

void loop() {
  char key = keypad.getKey();
  
  if (key) {
    if (key == '#') { // Tombol untuk memeriksa password
      if (strcmp(enteredPassword, password) == 0) {
        lcd.clear();
        lcd.print("Access Accepted");
        digitalWrite(greenLedPin, HIGH); // Nyalakan lampu hijau
        digitalWrite(redLedPin, LOW);    // Matikan lampu merah
      } else {
        lcd.clear();
        lcd.print("Invalid password");
        digitalWrite(greenLedPin, LOW);  // Matikan lampu hijau
        digitalWrite(redLedPin, HIGH);  // Nyalakan lampu merah
      }
      delay(2000);
      lcd.clear();
      lcd.print("Input Password:");
      memset(enteredPassword, 0, sizeof(enteredPassword));
      passwordIndex = 0;
    } else if (key == '*') { // Tombol untuk menghapus layar
      lcd.clear();
      lcd.print("Input Password:");
      memset(enteredPassword, 0, sizeof(enteredPassword));
      passwordIndex = 0;
      digitalWrite(greenLedPin, LOW); // Matikan lampu hijau
      digitalWrite(redLedPin, LOW);   // Matikan lampu merah
    } else {
      lcd.setCursor(passwordIndex, 1);
      lcd.print('*');
      enteredPassword[passwordIndex] = key;
      passwordIndex++;
      if (passwordIndex == 4) {
        passwordIndex = 0; // Reset index
      }
    }
  }
}

//@Rymutich '_' Ojo Lupa Ngopi