// INTELLEGENT POWER SYSTEM

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

//---Button Menu
#define BUP  4
#define BOK  3
#define BDN  2
#define KEYACC 6
#define KEYC  5 

#define lampBR  49
#define lampACC 51
#define lampC   53

#define PUSH LOW  //Ditekan
#define BOUN 10   

unsigned long pressTimer = 0;
unsigned long previousMillis = 0;
const long Delay = 500;

byte started = 0;
boolean jalan;

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  pinMode(BUP, INPUT_PULLUP);
  pinMode(BOK, INPUT_PULLUP);
  pinMode(BDN, INPUT_PULLUP);
  pinMode(KEYC, INPUT_PULLUP);
  pinMode(lampBR,  OUTPUT);
  pinMode(lampACC, OUTPUT);
  pinMode(lampC,   OUTPUT);

  digitalWrite(lampBR, LOW);
  digitalWrite(lampACC, LOW);
  digitalWrite(lampC, LOW);
  lcd.setCursor(6, 0); lcd.print("NEW SPMC");
  lcd.setCursor(3, 1); lcd.print("PT.KARYA MULTI");
  lcd.setCursor(1, 2); lcd.print("SOLUTION INDONESIA");
  delay(2000);
  lcd.clear();
  jalan = false;
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= Delay) {
    previousMillis = currentMillis;
    keyLogic();
  }
}

void afterON(){
  if (digitalRead(BOK) == LOW) {  // Jika tombol ditekan
    if (pressTimer == 0) {    // Jika belum ada waktu awal yang disimpan
      pressTimer = millis();  // Simpan waktu saat ini
    }
    if (millis() - pressTimer >= 2000) { // Cek apakah sudah 3 detik
      lcd.setCursor(0, 0); lcd.print("Select Category?    ");
      lcd.setCursor(0, 1); lcd.print("                    ");
      setMenu();
    }
  } else { // Jika tombol dilepas
    pressTimer = 0;          // Reset waktu awal
    lcd.setCursor(0,0); lcd.print("KEY.SW.A (ON)  ");
    lcd.setCursor(0,1); lcd.print("C.UNIT (ON)    ");
  }
}

void keyLogic() {
  if(!jalan){
    if (digitalRead(KEYACC) == PUSH) {
      lcd.setCursor(0,0); lcd.print("KEY.SW.BR (ON)  ");
      lcd.setCursor(0,1); lcd.print("KEY.SW.ACC (ON) ");
      digitalWrite(lampBR, HIGH);
      digitalWrite(lampACC, HIGH);
      jalan = true;
    } else if (digitalRead(KEYACC) != PUSH) {
      digitalWrite(lampBR, LOW);
      digitalWrite(lampACC, LOW);
      digitalWrite(lampC, LOW);
      started = 0;
      lcd.setCursor(0,0); lcd.print("KEY.SW.A (OFF)  ");
      lcd.setCursor(0,1); lcd.print("C.UNIT (OFF)    ");
    }
  } 
  else if (jalan && digitalRead(KEYACC) != PUSH) {jalan = false;} 

  else if (jalan && (digitalRead(KEYC) == PUSH)) {
    delay(BOUN);
    while(digitalRead(KEYC) == PUSH){}
    started = 1;
  }

  if(started == 1){
    if (digitalRead(KEYACC) != PUSH) {
      lcd.setCursor(0,0); lcd.print("KEY.SW.A (OFF)  ");
      lcd.setCursor(0,1); lcd.print("C.UNIT (OFF)    ");
      digitalWrite(lampBR, LOW);
      digitalWrite(lampACC, LOW);
      digitalWrite(lampC, LOW);
      jalan = false;
    } else {
      digitalWrite(lampC, HIGH);
      afterON();
    }
  }
}
UP
OK
DOWN
KEY OFF/ON
KEY STARTED
C
ACC
BR