#define BLYNK_PRINT Serial

#define BLYNK_TEMPLATE_ID   "TMPLLyEcAd2D"
#define LED 23
#define ECHO_PIN 12
#define TRIG_PIN 13

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

const int DHT_PIN = 15;
DHTesp dhtSensor;

long durasi;
int jarak;

char auth[] = "Eaa5Lf19zYYi--5Kh8Z_9wb9h8OGW_01";
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

BLYNK_WRITE(V2)
{
 int pinValue = param.asInt();

 if(param.asInt()==1){
 digitalWrite(LED,HIGH);
 Serial.println("LED ON");
 }
 else{
 digitalWrite(LED,LOW);
 Serial.println("LED OFF");
 }
}

void sendSensor()
{
 TempAndHumidity  data = dhtSensor.getTempAndHumidity();
 Serial.println("Temp: " + String(data.temperature, 2) + "°C");
 Serial.println("Humidity: " + String(data.humidity, 1) + "%");
 Serial.print("Jarak (cm): ");
 Serial.println(jarak);
 Serial.println("---");
 Blynk.virtualWrite(V0, data.temperature); //mengirimkan data ke Virtual pin di Blynk Cloud
 Blynk.virtualWrite(V1, data.humidity); //mengirimkan data ke Virtual pin di Blynk Cloud
}

void sendJarak ()
{
  Blynk.virtualWrite(V3, jarak);
}

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

void loop()
{
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(5);

  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  durasi = pulseIn(ECHO_PIN, HIGH);
  jarak = durasi * 0.034/2;

  Blynk.run();
  timer.run();
}