#include <IRremote.h>
#include <LiquidCrystal_I2C.h>

#define PIN_RECEIVER 2   // Signal Pin of IR receiver
LiquidCrystal_I2C lcd(0x27, 20, 4);
IRrecv receiver(PIN_RECEIVER);
bool f_remote, f_arus;
int sensorValue = 0;
int  outVal = 0;
int remoteVal = 0;
int resultAnalog, resutlRemote;
const byte relay = 13;
const int jumlahLed = 10;  // Tentukan jumlah LED yang akan digunakan
int pinLed[jumlahLed] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // Tentukan pin untuk masing-masing LED
int delayVal = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
  for (int i = 0; i < jumlahLed; i++) {
    pinMode(pinLed[i], OUTPUT);
    digitalWrite(pinLed[i], LOW);  // Awalnya matikan semua LED
  }
  ledOn();
  delay(1000);
  ledOff();

  f_arus = false;
  f_remote = false;
  digitalWrite(relay, LOW);
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  receiver.enableIRIn(); // Start the receiver
}

void loop() {
  delayRemote();
  delaySensor();
}

//-------------------------------------------

void delayRemote() {
  readRemote();
  if (resutlRemote > -1) {
    Serial.print("Data Remote: ");
    Serial.println(resutlRemote);
    delayVal = 100;
    ledOn();
    digitalWrite(relay, HIGH);
    //f_remote = true;
    ledOff();
  }

}
//-------------------------------
void delaySensor() {
  resultAnalog = readAnalog();
  Serial.print("Data Analog: ");
  Serial.println(resultAnalog);
  if (resultAnalog > 2) {
    digitalWrite(relay, HIGH);
  } else  if (resultAnalog <= 2) {
    delayVal = 500;
    ledOn();
    digitalWrite(relay, LOW);
    f_remote = false;
    ledOff();
  }

}


//------------------------------------

void ledOn() {
  for (int i = 0; i < jumlahLed; i++) {
    digitalWrite(pinLed[i], HIGH);  // Nyalakan LED
    delay(delayVal);  // Tunggu selama 100ms
  }
}

void ledOff() {
  // Mematikan semua LED
  for (int i = 0; i < jumlahLed; i++) {
    digitalWrite(pinLed[i], LOW);  // Matikan LED
  }
}

int readRemote() {
  if (receiver.decode()) {
    int remoteVal = receiver.decodedIRData.command;
    //Serial.print("Data Remote: ");
    //Serial.println(remoteVal);
    receiver.resume();
    return remoteVal;
  } else {
    return -1;  // Nilai sentinal jika tidak ada data remote yang terbaca
  }
}

int readAnalog() {
  int sensorValue = analogRead(A0);
  int outVal = map(sensorValue, 0, 1023, 0, 10);
  return outVal;
}