#define BLYNK_TEMPLATE_ID "TMPLN67KH-IE"
#define BLYNK_TEMPLATE_NAME "Blynk182"
#define BLYNK_AUTH_TOKEN "o0g_fcocfg1Pa_iOA98s7BZKht6lt5Ty"


#define BLYNK_PRINT Serial

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

char auth[] = "o0g_fcocfg1Pa_iOA98s7BZKht6lt5Ty";

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

BlynkTimer timer;

#define ECHO_PIN 5
#define TRIG_PIN 4
int merah, kuning, hijau;

void setup() {
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(15, OUTPUT); //Hijau
  pinMode(18, OUTPUT); // Kuning
  pinMode(19, OUTPUT); //Merah
}

float readDistanceCM() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  return duration * 0.034 / 2;
  
}

void loop() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 0.034 / 2;
  Blynk.virtualWrite(V7, distance);

  Serial.print("Jarak: ");
  Serial.println(distance);
  delay(100);
  

if(distance > 100){
  digitalWrite(15, HIGH );
  digitalWrite(18, LOW );
  digitalWrite(19, LOW );
  merah = 0;
  kuning = 0;
  hijau = 1;
  Serial.println("Kondisi pasang air: Aman");
}
else if(distance <60 && distance >= 20){
  digitalWrite(15, LOW);
  digitalWrite(18, HIGH);
  digitalWrite(19, LOW);
  merah = 0;
  kuning = 1;
  hijau = 0;
  Serial.println("Kondisi pasang air: Waspada air pasang");

}
else if(distance<20){
  digitalWrite(15, LOW);
  digitalWrite(18, LOW);
  digitalWrite(19, HIGH);
  merah = 1;
  kuning = 0;
  hijau = 0;
  Serial.println("Kondisi pasang air: Air Pasang! Bahaya!!");
}
  Blynk.virtualWrite(V4, merah);
  Blynk.virtualWrite(V5, kuning);
  Blynk.virtualWrite(V6, hijau);
  delay(100);

}