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

const int pinLED = 23;
const int pinLDR = A0;
const int buzzerPin = 2;
int adcValue = 0;

// LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;

void setup()
{
  // inisiasi Serial comm dengan baud rate 115200
  lcd.init();
  lcd.backlight();
  pinMode(buzzerPin, OUTPUT);
  pinMode(pinLED, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  // akuisisi nilai ADC sensor LDR
  adcValue = analogRead(pinLDR);
  //  dokumentasi dari wokwi
  //  float voltage = conversion_adcValue / 1024. * 5;
  //  float resistance = 2000 * voltage / (1 - voltage / 5);
  //  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  // 4095 = adc esp32 12-bit, bukan 10 bit
  float voltage = adcValue / 4095. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  lcd.setCursor(0, 0);
  lcd.print("Room: ");
  if (lux > 100) {
    lcd.print("Danger");
    digitalWrite(pinLED, LOW);
    tone(buzzerPin, 262);
    delay(500);
  } else if (lux > 10){
    lcd.print("Light ");
    noTone(buzzerPin);
    digitalWrite(pinLED, LOW);
  } else {
    lcd.print("Dark  ");
    digitalWrite(pinLED, HIGH);
    noTone(buzzerPin);
  }

  lcd.setCursor(0, 1);
  lcd.print("Lux : ");
  lcd.print(lux);
  lcd.print("          ");

  //  jeda akuisisi data
  delay(1000);
}