#define BLYNK_TEMPLATE_ID "TMPL6A5Fxm5jf"
#define BLYNK_TEMPLATE_NAME "Embedded Final"
#define BLYNK_AUTH_TOKEN "lKhuCU9PiFCBdZI2JBC8V_tEvg_ySRdQ"
 
#include <BlynkSimpleEsp32.h>
#include <WiFi.h>
#include <ESP32Servo.h> // Include the ESP32Servo library
#include <HX711.h>      // Include the HX711 library

#define SERVO_PIN 16 // Pin for the servo motor (D14 on ESP32)
#define SWITCH_PIN1 V3
#define SWITCH_PIN2 V4
#define SCK_PIN V26   // Pin for the HX711 SCK pin
#define DT_PIN V27    // Pin for the HX711 DT pin
#define LED_PIN 22    // Pin for the LED

BlynkTimer timer;
HX711 scale;

const char *ssid = "Wokwi-GUEST";
const char *password = "";

int sliderValue = 0;
bool switchState1 = false;
bool switchState2 = false;
int interval = 0; // Global variable to store the blinking interval

Servo servo; // Create a servo object

void setup() {
  Serial.begin(9600);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");

  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, password);

  servo.attach(SERVO_PIN); // Attach the servo to the specified pin

  scale.begin(DT_PIN, SCK_PIN); // Initialize the HX711 sensor
  scale.set_scale(430);        // Set the calibration factor (example value, adjust as needed)

  timer.setInterval(1000L, moveServo); // Call the moveServo function every second

  pinMode(LED_PIN, OUTPUT); // Set LED pin as output
}

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

  // Read the sensor
  float sensorReading = scale.get_units(10) * 1000; // Convert KG to grams
  Serial.print("Weight: ");
  Serial.print(sensorReading);
  Serial.println(" g");
  

  // Check if the weight reading is below 250 grams
  if (sensorReading < 250) {
    // Turn on the LED
    digitalWrite(LED_PIN, HIGH);
  } else {
    // Turn off the LED
    digitalWrite(LED_PIN, LOW);
  }

  delay(1000); // Delay for stability
}

BLYNK_WRITE(SWITCH_PIN1)
{
  int buttonValue = param.asInt(); // Read the value of the button (0 or 1)
  interval = buttonValue;          // Set the global interval variable
  Serial.print("Button 1 value: ");
  Serial.println(buttonValue);
}

BLYNK_WRITE(SWITCH_PIN2)
{
  int buttonValue = param.asInt(); // Read the value of the button (0 or 1)
  interval = buttonValue;          // Set the global interval variable
  Serial.print("Button 2 value: ");
  Serial.println(buttonValue);
}

void moveServo()
{
  if (interval > 0)
  {
    servo.write(0);         // Move the servo to 0 degrees
    delay(1000);            // Wait for 1 second
    servo.write(180);       // Move the servo to 180 degrees
    delay((interval - 1) * 1000); // Wait for the remaining duration
  }
  else
  {
    servo.write(90); // If both switches are off, keep the servo at 90 degrees
  }
}