#define BLYNK_TEMPLATE_ID "TMPL6oRu5wFsA"
#define BLYNK_TEMPLATE_NAME "thinkiot"
#define BLYNK_AUTH_TOKEN "UOvPBwqoneJ0iBwY1P3P7VkK__WFaI1i"

// Define the GPIO pins for the ultrasonic sensor

#define trigPin 5
#define  echoPin 18
#include <DHTesp.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <NewPing.h>
#include <BlynkSimpleEsp32.h>
#define DHTPIN 15
#define LED_PIN 21

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

BlynkTimer timer;

// Create an instance of the NewPing library
NewPing sonar(trigPin, echoPin);
void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  dht.setup(DHTPIN, DHTesp::DHT22); // Initialize DHT sensor
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(2000L, sendDHTData); // Send DHT data every 2 seconds
    Serial.begin(115200);

  Blynk.begin(auth, ssid, pass);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

BLYNK_WRITE(V3) {
  int buttonState = param.asInt();
  if (buttonState == 1) {
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
}

void sendDHTData() {
  float t = dht.getTemperature();
  float h = dht.getHumidity();
  
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Blynk.virtualWrite(V0, t);
  Blynk.virtualWrite(V1, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print("%\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" °C");
}

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

  // Trigger an ultrasonic pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the distance
  unsigned int distance_cm = sonar.ping_cm();

  // Send the distance data to Blynk
  Blynk.virtualWrite(V4, distance_cm);  // Use V1 as a display widget in your Blynk app

  Serial.print("Distance: ");
  Serial.print(distance_cm);
  Serial.println(" cm");

  delay(2000); // Delay between measurements
}