#define BLYNK_TEMPLATE_ID "TMPLIHNCAlaO"
#define BLYNK_DEVICE_NAME "NodeMCU"
#define BLYNK_AUTH_TOKEN "qWweW5DHuSdXBgNkyYpcw40IVRAQZ7yg"

const int trigPin = 2;
const int echoPin = 4;
int duration, cm;
int p;

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

BlynkTimer timer; 

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

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

void myTimer() 
{
  Blynk.virtualWrite(V0,p);
}

void setup() 
{ 
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  lcd.init();
  lcd.backlight();
  timer.setInterval(1000, myTimer); 
}

void loop() 
{
  Blynk.run();
  timer.run(); 
  
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  delay(100);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  cm = microsecondsToCentimeters(duration);
  p = ((cm/405.00)*100) ;
  
  Serial.print("Space in bin : ");
  Serial.print(p);
  Serial.println("%");
  
  if((p > 10)&&(p <= 100))
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Space in bin :");
    lcd.setCursor(8,1);
    lcd.print(p);
    lcd.println("%");
  }
  else if(p <= 10)
  {
    lcd.clear();
    delay(1000);
    lcd.setCursor(0,0);
    lcd.print("Space : ");
    lcd.setCursor(8,0);
    lcd.print(p);
    lcd.print("%");
    lcd.setCursor(0,1);
    lcd.println("Collect the bin!");
  }
  delay(1000);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}