#include <IRremote.h>
#include <LiquidCrystal_I2C.h>
#include<TimerOne.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 = 200;
int delayLedAry ;
int delayLedRelay;

int millsecLedAry, millsecRelay, i;
bool f_intLed;
bool f_relayState;
bool fLockRelay;



void setup() {
  // put your setup code here, to run once:
  Timer1.initialize(1000); // set a timer of length 1000000 microseconds (or 1 sec - or 1Hz)
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
  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
  }

  f_arus = false;
  f_remote = false;
  f_intLed = false;
  f_relayState = false;
  fLockRelay = false;
  digitalWrite(relay, LOW);
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  receiver.enableIRIn(); // Start the receiver
  delayLedAry = 50;
  delayLedRelay=500;
}

void loop() {
  cekRemote();
  readAnalog();
  CmpSensor();
  lcd.setCursor(0, 0);
  lcd.print("Remote: ");
  lcd.setCursor(8, 0);
  lcd.print(remoteVal);
  lcd.print(" ");

  lcd.setCursor(0, 1);
  lcd.print("Analog: ");
  lcd.setCursor(8, 1);
  lcd.print(resultAnalog);
  lcd.print(" ");

}
//-------------------------------------------
void cekRemote() {
  readRemote();
  if (remoteVal > 0 ) {
    delayLedAry = 500;
    delayLedRelay=10000;
    f_relayState = true;
    f_remote = true;
    f_arus = true;
    remoteVal = 0;
  }
}
//-------------------------------
void CmpSensor() {
  
    if (resultAnalog > 2) {
      delayLedRelay=20000;
      fLockRelay = true;
    } else   {
      fLockRelay = false;
      delayLedAry = 50;
    }
 
}

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

void readRemote() {
  if (receiver.decode()) {
    remoteVal = receiver.decodedIRData.command;
    Serial.print("Data Remote: ");
    Serial.println(remoteVal);
    receiver.resume();
  }
}

void readAnalog() {
  resultAnalog = map(analogRead(A0), 0, 1023, 0, 10);
  Serial.print("Data Analog: ");
  Serial.println(resultAnalog);

}