/*
  iot-technology-ftbs
  program ini menggunakanESP32 dan terhubungan dengan aplikasi Blynk Lagacy
*/
#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "T1234567890"
#define BLYNK_TEMPLATE_NAME "poject3"
#define BLYNK_AUTH_TOKEN "X9DiYKklb8DFHjMuU_80fshiepgAPL57"

#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 13
#define LED2 12
#define LED3 14
#define LED4 27
#define LED5 26


DHTesp dhtSensor;
const int DHT_PIN = 15;

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


void setup()
{
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(Trig, OUTPUT);
  pinMode(Echo, INPUT);
  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();
}

// 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;
}

BLYNK_WRITE (V1)
{
  digitalWrite(LED1, param.asInt());

}

BLYNK_WRITE (V2)
{
  digitalWrite(LED2, param.asInt());
}


BLYNK_WRITE (V3)
{
  digitalWrite(LED3, param.asInt());
}

BLYNK_WRITE (V4)
{
  digitalWrite(LED4, param.asInt());
}

BLYNK_WRITE (V5)
{
  digitalWrite(LED5, param.asInt());
}