#include <Arduino.h>
#include "soc/rtc.h"
#include "HX711.h"
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <PubSubClient.h>
const int LOADCELL_DOUT_PIN = 16;
const int LOADCELL_SCK_PIN = 4;
LiquidCrystal_I2C lcd(0x27, 16, 2);
HX711 scale;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp32/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
#define LED_PIN 0
#define BUZZER_PIN 12
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Connect!");
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Berat: ");
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish(topic, "Hi EMQX I'm ESP32 ^^");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
scale.set_scale();
delay(2000);
float berat = scale.get_units(10) / 420.00;
if (berat > 1) {
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
tone(12, 262, 250);
lcd.setCursor(7, 0);
lcd.print(berat, 2);
Serial.print("Berat: ");
Serial.println(berat);
digitalWrite(LED_PIN, LOW);
} else {
lcd.setCursor(7, 0);
lcd.print(berat, 2);
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
}
String beratStr = String(berat, 2);
delay(1000);
client.publish(topic, beratStr.c_str());
client.subscribe(topic);
}