#include <ESP32Servo.h> // Library for servo control on ESP32
#include <HX711.h> // Library for HX711 load cell
#define TRIG_PIN 25 // Ultrasonic sensor Trig pin
#define ECHO_PIN 26 // Ultrasonic sensor Echo pin
#define BUZZER_PIN 19 // Buzzer pin
// 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;
// Servo Setup
Servo myServo;
int servoPos = 0; // Initial position for the servo
void setup() {
Serial.begin(115200);
// Ultrasonic Sensor Setup
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Buzzer Setup
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW); // Ensure buzzer is off initially
// Load Cell Initialization
loadCell.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
loadCell.set_scale(1000.0); // Calibration factor (adjust as needed)
loadCell.tare(); // Reset scale to 0
// Servo Initialization
myServo.attach(SERVO_PIN);
myServo.write(servoPos); // Set initial servo position to 0 degrees (closed)
}
long ultraSonic() {
long duration, distance_mm;
// Trigger ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure duration of echo return pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in millimeters
distance_mm = (duration * 0.034 / 2) * 10;
return distance_mm;
}
void beepBuzzer(int times, int delayTime) {
for (int i = 0; i < times; i++) {
digitalWrite(BUZZER_PIN, HIGH); // Turn on buzzer
delay(delayTime);
digitalWrite(BUZZER_PIN, LOW); // Turn off buzzer
delay(delayTime);
}
}
void loop() {
long distance_mm = ultraSonic();
Serial.print("Distance: ");
Serial.print(distance_mm);
Serial.println(" mm");
// Buzzer Control
if (distance_mm > 3000) { // 3000 mm equals 300 cm
beepBuzzer(3, 200); // Beep 5 times with 200 ms interval
}
// Load Cell Reading
if (loadCell.is_ready()) {
float weight = loadCell.get_units(5) * 1000; // Convert kg to grams
Serial.print("Weight: ");
Serial.print(weight, 2);
Serial.println(" g");
// Servo control based on weight
if (weight <= 0) { // Open servo if weight is less than or equal to 0 grams
myServo.write(180);
} else if (weight >= 200) { // Close servo if weight is more than or equal to 200 grams
myServo.write(90);
}
} else {
Serial.println("HX711 not found");
}
delay(1000); // Delay between readings for stability
}