#include <ESP32Servo.h> // Library for servo control on ESP32
#include <HX711.h> // Library for HX711 load cell
// Pin Definitions
const int SERVO_PIN = 18; // Servo control pin
const int LOADCELL_DOUT_PIN = 4; // HX711 DOUT
const int LOADCELL_SCK_PIN = 5; // HX711 SCK
// Load Cell Setup
HX711 loadCell;
// float weightThreshold = 500.0; // Threshold weight set to 500 grams (0.5 kg)
// Servo Setup
Servo myServo;
int servoPos = 0; // Initial position for the servo
void setup() {
Serial.begin(115200);
// Load Cell Initialization
loadCell.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
loadCell.set_scale(7050.0); // Calibration factor (adjust this as needed)
loadCell.tare(); // Reset the scale to 0
// Servo Initialization
myServo.attach(SERVO_PIN);
myServo.write(servoPos); // Set initial servo position to 0 degrees (closed)
}
void loop() {
// Load Cell Reading
if (loadCell.is_ready()) {
float weight = loadCell.get_units(5); // Average of 5 readings for stability
Serial.print("Weight: ");
Serial.print(weight,2);
Serial.println("kg");
myServo.write(0);
delay(1000);
myServo.write(90);
delay(1000);
myServo.write(180);
if(weight <= 0.1){
}else{}
// Control the Servo based on weight threshold
// if (weight <= 0.1) {
// servoPos = 90; // Rotate servo to 90 degrees (open position)
// myServo.write(servoPos);
// Serial.println("Servo Opened - Weight is 0.5 kg or less");
// } else {
// servoPos = 0; // Return servo to 0 degrees (closed position)
// myServo.write(servoPos);
// Serial.println("Servo Closed - Weight is above 0.5 kg");
// }
} else {
Serial.println("HX711 not found");
}
delay(500); // Delay between readings for stability
}