#include <WiFi.h>
#include <PubSubClient.h>
#include <HX711.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Broker details
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* mqttTopic = "esp32/loadcell";
// HX711 pins
#define DT 22
#define SCK 23
HX711 scale;
// MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
void connectToWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
void connectToMQTT() {
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect, rc=");
Serial.print(client.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
scale.begin(DT, SCK);
scale.set_scale(4.2); // Set the scale factor here if needed
scale.tare(); // Reset the scale to 0
connectToWiFi();
client.setServer(mqttServer, mqttPort);
}
void loop() {
if (!client.connected()) {
connectToMQTT();
}
client.loop();
// Read weight from loadcell
if (scale.is_ready()) {
float weight = scale.get_units();
Serial.print("Weight: ");
Serial.println(weight);
// Publish data to MQTT
String payload = String(weight);
client.publish(mqttTopic, payload.c_str());
delay(1000); // Send data every 1 second
} else {
Serial.println("HX711 not ready");
}
}