#include <Arduino.h>
#include "HX711.h"
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 12; // DOUT pin on HX711
const int LOADCELL_SCK_PIN = 13; // SCK pin on HX711
HX711 scale; // Declare the HX711 object globally
// Relay module control pin
const int relayPin = 14; // GPIO pin connected to the relay module
// Calibration factor (fixed for 5 kg weight based on raw value of 2100)
float raw_value_per_kg = 420.0; // Calibration factor for 5 kg (2100 raw value)
// Flag to indicate calibration status
bool isCalibrated = true;
void setup() {
Serial.begin(115200);
Serial.println("ESP8266 Weight Detection and Relay Control");
// Initialize HX711
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.tare(); // Reset scale to 0
Serial.println("Scale initialized. Calibration factor set for 5 kg.");
// Initialize the relay module pin
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // Ensure relay is OFF initially
}
void loop() {
if (scale.is_ready() && isCalibrated) {
// Get raw ADC value
long raw_value = scale.get_units(10); // Average of 10 readings
// Convert raw ADC value to kilograms
float weight_kg = raw_value / raw_value_per_kg;
// Display weight
Serial.print("Raw Value: ");
Serial.print(raw_value);
Serial.print(", Weight: ");
Serial.print(weight_kg, 2); // 2 decimal places
Serial.println(" kg");
// Control the relay based on weight
if (weight_kg > 0) {
digitalWrite(relayPin, HIGH); // Activate relay (lock engaged)
Serial.println("Relay ON (Locking)");
} else {
digitalWrite(relayPin, LOW); // Deactivate relay (lock disengaged)
Serial.println("Relay OFF (Unlocking)");
}
} else if (!scale.is_ready()) {
Serial.println("HX711 not detected. Check wiring.");
}
delay(2000); // Delay for 2 seconds
}