WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
Serial.print("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
client.setServer(MQTT_SERVER, 1883);
setupOTA();
// Setting up heartbeat
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
static int lastValue = 0;
int value;
if (!client.connected()) {
reconnect();
}
value = scale.read_average(5);
Serial.println(value);
// Only publish new value if difference of 500 or more
if (abs(lastValue - value) >= 500) {
String value_str = String(value);
client.publish(STATE_TOPIC, (char *)value_str.c_str());
lastValue = value;
}
// Handle OTA
ArduinoOTA.handle();
// Process MQTT tasks
client.loop();
// Heartbeat
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
delay(250);
scale.power_down(); // put the ADC in sleep mode
delay(1000);
scale.power_up();
platform: mqtt
state_topic: "home/bedroom/bed"
name: "Raw Master Bed Weight Measurement"
unit_of_measurement: "available"
This is my configuration in the sensor
include
include
include
include
include
WiFiClient wifiClient; PubSubClient client(wifiClient);
// Pin Settings
define HX711_DT 5
define HX711_SCK 4
HX711 scale(HX711_DT, HX711_SCK);
// connection settings
define wifi_ssid "hir..................."
define wifi_password "n.............."
// // MQTT Settings
define HOSTNAME "Raw Master Bed Weight Measurement"
define MQTT_SERVER "192.168.1..........."
define MQTT_USER "c........................."
define MQTT_PASSWORD "c................"
define MQTT_PORT 1883
define STATE_TOPIC "home/bedroom/bed"
define AVAILABILITY_TOPIC "home/bedroom/bed/available"
/**** FOR OTA **/ // OTA Settings
define OTA_PORT 8266
void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(HOSTNAME)) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(AVAILABILITY_TOPIC, "online"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }
void setupOTA() { ArduinoOTA.setPort(OTA_PORT); ArduinoOTA.setHostname(HOSTNAME);
}
void setup() { Serial.begin(115200); Serial.println();
}
void loop() { static int lastValue = 0; int value;
}