//#define BLYNK_TEMPLATE_ID "TMPLxcfn51g5"
//#define BLYNK_DEVICE_NAME "DHT22 IoT4 7"
//#define BLYNK_AUTH_TOKEN "FbBef1Vmx70Byq8nMFfLTRoGtNlEsgf0"

#define PIN_LDR 34
#define LED 25
#define BLYNK_TEMPLATE_ID "TMPLZ7zwlBlj"
#define BLYNK_DEVICE_NAME "DHT22"
#define BLYNK_AUTH_TOKEN "M29LJObIDdB_LMXKVHabifs1WYp38c3x"


#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

const float GAMMA = 0.7;
const float RL10 = 50;


char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;


void alertLux(float lux){
  if(lux >= 50){
    Serial.println("Terang");
    digitalWrite(LED, LOW);
    Blynk.virtualWrite(V5, "Terang");
  } else {
    Serial.println("Gelap");
    digitalWrite(LED, HIGH);
    Blynk.virtualWrite(V5, "Gelap"); 
  } 
}

void readLux(){
  int value = analogRead(PIN_LDR);
  float voltage = value * 5 / 4095.0;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10,GAMMA) / resistance, (1/GAMMA));
  Serial.print("lux: ");
  Serial.println(lux);
  Blynk.virtualWrite(V7, lux);
  alertLux(lux);
}
void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  digitalWrite(LED, LOW);
  pinMode(PIN_LDR, INPUT);
  pinMode(LED, OUTPUT);
  timer.setInterval(1000L, readLux);
}

void loop()
{
  Blynk.run();
  timer.run();
}