#define BLYNK_TEMPLATE_ID "TMPLEmdn9ZUO"
#define BLYNK_DEVICE_NAME "alrmair"
//#define BLYNK_AUTH_TOKEN "FqarV8UCxFC8tjv-dyYdURn0CxMB6AQf"
//#define BLYNK_TEMPLATE_ID "TMPLAhRooRvV"
//#define BLYNK_DEVICE_NAME "dht22"
//#define BLYNK_AUTH_TOKEN "Wc9IACtbD2EME34t4wtyb9fGEiQwVAA5"

#define ECHO_PIN 22
#define TRIG_PIN 23
#define Hijau 12
#define Kuning 14
#define Merah 15

char auth[] = "FqarV8UCxFC8tjv-dyYdURn0CxMB6AQf";

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
//#include "DHTesp.h"



#define LED 2
#define BLYNK_PRINT Serial

float X=400/397.63;

BLYNK_CONNECTED() {
   Blynk.syncVirtual(V2); //Sesuaikan dengan Virutal Pin yg dipakai
}
bool toggleState_1 = LOW;
BLYNK_WRITE(V2){ //Sesuaikan dengan Virutal Pin yg dipakai
  toggleState_1 = param.asInt();
  if(toggleState_1 == 1){
    digitalWrite(2, HIGH);
  }
  else { 
    digitalWrite(2, LOW);
  }
}

//const int DHT_PIN = 15;
//DHTesp dhtSensor;

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

BlynkTimer timer;

//Membaca Virtual Pin dari Server Blynk


void sendSensor()
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  //Read ultrasonic signal
  int duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 0.034 * X / 2;
  float t_air = 350-distance;

  if(t_air >= 200){
    digitalWrite(Merah, 1);
    digitalWrite(Kuning, 0);
    digitalWrite(Hijau, 0);
    Serial.print("Bahaya!! ");
  }else if(t_air >= 100){
    digitalWrite(Kuning, 1);
    digitalWrite(Hijau, 0);
    digitalWrite(Merah, 0);
    Serial.print("Waspada! ");
  }else{
    digitalWrite(Hijau, 1);
    digitalWrite(Kuning, 0);
    digitalWrite(Merah, 0);
    Serial.print("Aman ");
  }
  Serial.print("tinggi air: ");
  Serial.print(t_air);
  Serial.println(" CM");

 /*TempAndHumidity  data = dhtSensor.getTempAndHumidity();
 Serial.println("Temp: " + String(data.temperature, 2) + "°C");
 Serial.println("Humidity: " + String(data.humidity, 1) + "%");
 Serial.println("---");*/
 //BLYNK_CONNECTED();
 Blynk.virtualWrite(V0, t_air);
 Blynk.virtualWrite(V1, Hijau);
 Blynk.virtualWrite(V2, Kuning);
 Blynk.virtualWrite(V3, Merah);
 //Blynk.virtualWrite(V1, data.humidity);
 //BLYNK_WRITE(V2); //mengirimkan data ke Virtual pin di Blynk Cloud
 delay(100);
}

void setup()
{
  
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(Hijau, OUTPUT);
  pinMode(Kuning, OUTPUT);
  pinMode(Merah, OUTPUT);
  Blynk.begin(auth, ssid, pass);
  pinMode(LED, OUTPUT);
  //dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  timer.setInterval(2000L, sendSensor);
}

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