#define BLYNK_TEMPLATE_ID "TMPL6Kffd5xpT"
#define BLYNK_TEMPLATE_NAME "ESP32"
#define BLYNK_AUTH_TOKEN "sDrlXHvVr9M9yPP_Vm-WikbuZ6GD9poQ"

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

#define DHTPIN 18  // Pin tempat DHT11 terhubung
#define DHTTYPE DHT22  // Tipe sensor DHT

#define TRIGGER_PIN 25 // Pin trigger ultrasonik
#define ECHO_PIN 26    // Pin echo ultrasonik

#define LED_PIN 5    // Pin LED
#define BUTTON_PIN 4  // Pin push button

DHT dht(DHTPIN, DHTTYPE);
char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

bool ledState = false; // Untuk melacak keadaan LED

void setup() {
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT); // Tombol didefinisikan sebagai INPUT tanpa internal pull-up

  dht.begin();
}

void loop() {
  Blynk.run();
  
  // Membaca suhu dan kelembaban dari DHT11
  float humidity = dht.readHumidity();
  float temperatureCelsius = dht.readTemperature(); // Suhu dalam Celsius
  float temperatureFahrenheit = (temperatureCelsius * 9.0 / 5.0) + 32.0; // Konversi ke Fahrenheit
  float temperatureKelvin = temperatureCelsius + 273.15; // Konversi ke Kelvin

  // Membaca jarak dari sensor ultrasonik
  float distance = getDistance();

  // Membaca status tombol push
  int buttonState = digitalRead(BUTTON_PIN);

  Serial.print("Suhu: ");
  Serial.print(temperatureCelsius);
  Serial.print("C, Kelembaban: ");
  Serial.print(humidity);
  Serial.print("%, Jarak: ");
  Serial.print(distance);
  Serial.print("cm, Tombol: ");
  Serial.println(buttonState);

  Blynk.virtualWrite(V1, temperatureCelsius); // Suhu dalam Celsius
  Blynk.virtualWrite(V2, temperatureFahrenheit); // Suhu dalam Fahrenheit
  Blynk.virtualWrite(V3, temperatureKelvin); // Suhu dalam Kelvin
  Blynk.virtualWrite(V4, humidity); // Kelembaban
  Blynk.virtualWrite(V5, distance); // Jarak
  Blynk.virtualWrite(V6, buttonState); // Status tombol

  // Mengatur LED berdasarkan tombol push
  if (buttonState == HIGH) {
    ledState = true; // LED dinyalakan saat tombol ditekan
  } else {
    ledState = false; // LED dimatikan saat tombol dilepaskan
  }
  digitalWrite(LED_PIN, ledState); // Set LED berdasarkan keadaan terbaru

  delay(200); // Delay untuk menghindari bouncing pada push button
}

float getDistance() {
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 0.034 / 2;

  return distance;
}

$abcdeabcde151015202530fghijfghij