// blynk
#define BLYNK_PRINT Serial  
#define BLYNK_TEMPLATE_ID "TMPL6gLcLmpit"
#define BLYNK_TEMPLATE_NAME "ESP32 Timbangan"
#define BLYNK_AUTH_TOKEN "iuOL5nrBRR7VtR0uiXG5_Ul2VIfizrm5"

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

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


BlynkTimer timer;

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

// HX711
#include <HX711.h>
#define DATA_PIN  4
#define CLOCK_PIN 2

int trig = 33;
int echo = 32;
long durasi, jarak;

HX711 hx711;
volatile float units;


void setup()
{
  // Debug console
  pinMode(trig, OUTPUT);  // Sets the trigPin as an Output
  pinMode(echo, INPUT);   // Sets the echoPin as an Inpu
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  hx711.begin(DATA_PIN, CLOCK_PIN);
  hx711.set_scale(420.0983);
  hx711.tare();

  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, sendSensor);
}

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

void sendSensor()
{
  units = hx711.get_units();
  Serial.println(units);
  delay(200);

  digitalWrite(trig, LOW);
  delayMicroseconds(8);
  digitalWrite(trig, HIGH);
  delayMicroseconds(8);
  digitalWrite(trig, LOW);
  delayMicroseconds(8);
  durasi = pulseIn(echo, HIGH);
  jarak = (durasi / 0.58) / 100;
  int tinggi_badan = 50 - jarak;

  lcd.setCursor(0, 1);
  lcd.print("           ");
  lcd.setCursor(0, 1);
  lcd.print("HEIGHT     ");
  lcd.print(String(tinggi_badan) + " cm");
  delay(250);

  lcd.setCursor(0, 0);
  lcd.print("           ");
  lcd.setCursor(0, 0);
  lcd.print("WEIGHT   ");
  lcd.print(String(units) + " kg");
  delay(250);

  // if(jarak <= 5)
  // {
  //   Blynk.tweet("My Arduino project is tweeting using @blynk_app and it’s awesome!\n #arduino #IoT #blynk");
  //   Blynk.notify("Post has been twitted");
  // }
  Blynk.virtualWrite(V19, tinggi_badan);
  Blynk.virtualWrite(V23, units);
  delay(1000);                        //Pause for 3 seconds and start measuring distance again
}