#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID "TMPL3kvUwVt7"
#define BLYNK_DEVICE_NAME "TestSensor"
//#define BLYNK_AUTH_TOKEN "Sz3PpKPJZdvIo0RcWfJRM81xua9DxYEK"

#include "BlynkSimpleEsp32.h"
#include "WiFi.h"
#include "WiFiClient.h"

// ultrasonic sensor
#define ECHO_PIN 2
#define TRIG_PIN 4

// LED
#define ledMerah 13
#define ledKuning 12
#define ledHijau 14
#define LED 27

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

double device = 350;

BlynkTimer timer;

BLYNK_WRITE(V0) {
  int pinValue = param.asInt();
  digitalWrite(LED,pinValue);
}

void sendSensor() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 0.034 / 2;

  if(distance > 150) {
    digitalWrite(ledHijau, HIGH);
    digitalWrite(ledKuning, LOW);
    digitalWrite(ledMerah, LOW);
  }
  else if(distance <= 150 && distance >= 100) {
    digitalWrite(ledHijau, LOW);
    digitalWrite(ledKuning, HIGH);
    digitalWrite(ledMerah, LOW);
  }
  else if(distance < 100) {
    digitalWrite(ledHijau, LOW);
    digitalWrite(ledKuning, LOW);
    digitalWrite(ledMerah, HIGH);
  }

  Blynk.virtualWrite(V0, device - distance); 
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);

  Serial.print("Tinggi air: ");
  Serial.print(device - distance);
  Serial.println(" cm");
}

void setup() {
   // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  Serial.begin(115200);

  // ultrasonic sensor
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  // LED
  pinMode(ledMerah, OUTPUT);
  pinMode(ledKuning, OUTPUT);
  pinMode(ledHijau, OUTPUT);
  pinMode(LED, OUTPUT);

  // Blynk
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(2000L, sendSensor);
}

void loop() {

  // put your main code here, to run repeatedly:
  //delay(10); // this speeds up the simulation
  Blynk.run();
  timer.run();
}