#include <Wire.h>
#include <HX711.h>
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "wokwi_GUEST";
const char* password = ""; // Kosongkan jika tidak ada kata sandi WiFi

const char* iftttWebhookKey = "bUNtH3W5MvY-PhcKb1GU4qqCG3M_liP8fHmD9fXHZen";
const char* iftttEventName = "add_to_spreadsheet";

HX711 scale;
const int loadCellDoutPin = 27;
const int loadCellSckPin = 26;

void setup() {
  Serial.begin(115200);
  scale.begin(loadCellDoutPin, loadCellSckPin);
  scale.set_scale();
  scale.tare();

  // Menghubungkan ESP32 ke WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  float weightValue = getWeight();
  sendWeightToGoogleSpreadsheet(weightValue);

  // Tambahkan penundaan (delay) di sini sesuai kebutuhan Anda
  delay(60000); // Kirim data setiap 1 menit (60000 milidetik)
}

float getWeight() {
  // Membaca berat dari Load Cell HX711
  return scale.get_units(10); // Membaca berat dalam gram
}

void sendWeightToGoogleSpreadsheet(float weight) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = "https://maker.ifttt.com/trigger/" + String(iftttEventName) + "/with/key/" + String(iftttWebhookKey) + "?value1=" + String(weight);
    http.begin(url);

    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
      Serial.println("Data terkirim dengan sukses");
    } else {
      Serial.println("Terjadi kesalahan saat mengirim data");
    }

    http.end();
  }
}