#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL6CQlSotBG"
#define BLYNK_TEMPLATE_NAME "Kelompok 2 Tempat Sampat Pintar"
#define BLYNK_AUTH_TOKEN "ZOm_TtAj1BGJsAs0qlyHXMXE4Hi0ClZ5"
#define ECHO_PIN 15
#define TRIG_PIN 4
#define LDR 5
const int servoPin = 2;
int a = 0;
int b =0;
int indikator = 27;

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

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

Servo myservo; 
BlynkTimer timer;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LDR, INPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LDR, OUTPUT);  
  pinMode(indikator, OUTPUT);  

  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, sendSensor);
  myservo.attach(2); 
  myservo.write(0);
  Blynk.virtualWrite(V2, 0);
  Blynk.virtualWrite(V5, "Tertutup");
  Blynk.virtualWrite(V4, "Tidak terdeteksi tangan ");
  Blynk.virtualWrite(V3, 0);
}

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

BLYNK_WRITE(V2){
  myservo.write(param.asInt());
  int pinValue = param.asInt();
  if (pinValue > 5) {
    digitalWrite(LDR, HIGH);
    Blynk.virtualWrite(V5, "Terbuka "+String(pinValue)+" Derajat");
    Blynk.virtualWrite(V4, "Tangan tidak terdeteksi");
  }else{
    digitalWrite(LDR, LOW);
    Blynk.virtualWrite(V4, "Tangan terdeteksi ");
    Blynk.virtualWrite(V5, "Terutup "+String(pinValue)+" Derajat");
  } 
  if (a == 1){
  Blynk.virtualWrite(V2, 0);
}
}
void sendSensor()
{
  digitalWrite (indikator, HIGH);
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  int duration = pulseIn(ECHO_PIN, HIGH);
  float distance = duration * 28.5;
  
  // KondisiSampah Penuh
  if (a == 0){
  if (distance >= 10 && distance <= 20){
    Blynk.virtualWrite(V1, "Sampah baru terisi ");
    Blynk.virtualWrite(V0, "Jangan dulu membersihkan sampah");

  }
  if (distance > 20 && distance <= 30){
    Blynk.virtualWrite(V1, "Sampah hampir penuh");
    Blynk.virtualWrite(V0, "Harap membersihkan sampah");
  }
  if (distance >30){
    Blynk.virtualWrite(V1, "Sampah penuh ");
    Blynk.virtualWrite(V0, "Angkut & bersihkan sampah");
    Blynk.virtualWrite(V5, "Katub Terbuka");
    Blynk.virtualWrite(V2, 0);
    digitalWrite(LDR, LOW);
    myservo.write(0);              
    delay(15);
 
  delay(100);  
  }
}
if (a == 1){
  Blynk.virtualWrite(V1, "Bersihkan sampah");  
}
}