#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL3XvWT_aYr"
#define BLYNK_TEMPLATE_NAME "poject3"
#define BLYNK_AUTH_TOKEN "rFi0f-_r4Nc94SPsGuA2k-DVSN2CKigs"

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

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

BlynkTimer timer;

#define LED1 23  // 
#define LED2 22  // 
#define LED3 21 // 
#define LED4 5  // 
#define LED5 25  // 
#define LED6 26  // 
#define LED7 27  // 
#define LED8 14  // 
#define LED9 12  // 
#define LED10 13  // 
// Array berisi semua pin LED
int ledPins[] = {LED1, LED2, LED3, LED4, LED5, LED6, LED7, LED8, LED9, LED10};


DHTesp dhtSensor;
const int DHT_PIN = 15;

#define Trig 18
#define Echo 19
float jarak = 0;
float ketinggian_air = 0;




void setup()
{
  // Gunakan perulangan untuk mengatur pinMode
  for (int i = 0; i < 10; i++) {
    pinMode(ledPins[i], OUTPUT);
  }

  // Menyalakan LED secara bergantian dari LED1 hingga LED10
  for (int i = 0; i < 10; i++) {
    digitalWrite(ledPins[i], HIGH);  // Nyalakan LED
    delay(300);                      // Tunggu selama 500 ms
    digitalWrite(ledPins[i], LOW);   // Matikan LED
  }

  pinMode(Trig, OUTPUT);
  pinMode(Echo, INPUT);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  Serial.begin(9600);


  //Blynk.begin(auth, ssid, pass);
  Blynk.begin(auth, ssid, pass, "iot.serangkota.go.id", 8080);
}

void loop()
{
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  baca_jarak();
  Blynk.virtualWrite(V12, data.temperature);
  Blynk.virtualWrite(V13, data.humidity);
  Blynk.virtualWrite(V14, ketinggian_air);

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


BLYNK_WRITE (V0)
{
  digitalWrite(LED1, param.asInt());
}

// baca jarak dari sensor ultra sonic
void baca_jarak()
{
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);

  int duration = pulseIn(Echo, HIGH);
  jarak = duration * 0.034 / 2;
  ketinggian_air = jarak;
}