Troubleshooting
Why a Node-RED dashboard shows stale MQTT sensor values
Short answer
A Serial Monitor reading proves only the stages before publish, so a stale Node-RED dashboard value comes from after: retained MQTT messages stored under generic topics, or conversions run on failed two-byte I2C reads. Clear the retained messages, gate each read on a two-byte return, publish one verified sample per 5000 ms interval, and move the topics to your own broker.
On this page
- Why does the Serial Monitor value not match the dashboard?
- Why does a retained MQTT message deliver an old value to a new subscriber?
- How do you prove each I2C read returned two bytes before converting?
- Why does the sampling loop stretch past the 5000 ms interval?
- Did the publish actually reach the broker?
- Why is a public broker the wrong home for plant sensor topics?
- What is the fastest fix order for a stale dashboard value?
- Questions asked
A temperature reading that is correct on the Serial Monitor and wrong on the Node-RED dashboard was almost always changed after the sensor: the sketch publishes Ctemp, Ftemp and humid as retained messages on generic topics to a shared public broker, and it converts I2C reads without checking that both bytes came back. So a reconnecting dashboard begins with whatever the broker has stored, and a failed read turns into a plausible number instead of an error. Clear the three retained messages first, gate every read on the byte count, publish one verified sample per interval from a nonblocking loop, and move the topics to a broker you operate. The sections below walk the path stage by stage and end each one with the decision.
Why does the Serial Monitor value not match the dashboard? #
The Serial Monitor print runs before client.publish(), so it proves the sensor, the I2C bus and the conversion but nothing about the message Node-RED receives; a stale dashboard value comes from the publish path, the broker's stored retained message, or another publisher on the same topics.
Treat the path as five stages: sensor to I2C, conversion on the ESP8266, serialization to text, broker, then Node-RED's MQTT-in node and dashboard widget. The print you trust sits between the third and fourth stage, so the fault lives in the two stages after it, or in an old value the broker delivers ahead of any live message. Take one observation per stage: the printed conversion value, the payload string in a debug panel, and what a second subscriber receives, in that order.
Decision: if the debug panel shows the same number the Serial Monitor prints, the device is innocent and the staleness is stored broker-side; go straight to the retained-message check.
Why does a retained MQTT message deliver an old value to a new subscriber? #
The sketch sets the retain flag to true on all three publishes — Ctemp, Ftemp, humid — so the broker stores the last payload per topic and hands it to every new subscriber immediately; that payload can be hours old and still overwrite what you expect to see.
An MQTT broker keeps one stored message per topic that was published with retain set, and it delivers that stored copy at subscribe time, ahead of live traffic. Every dashboard reconnect therefore starts from history: your previous test run, or whatever another client published last. Topic names are case-sensitive, and Ctemp is generic — on a shared broker, Ctemp and ctemp are different topics, and any other client that publishes to Ctemp replaces both the live stream and the stored value.
The protocol also defines the delete: publish a zero-length payload to the topic with retain still set, and the broker drops the stored message. For live telemetry, retention buys staleness and nothing else, so set the flag false in all three client.publish() calls and redeploy.
Decision: clear the three retained messages once, turn retain off, and compare the dashboard against the print; if they now agree within one sample, retention was the whole fault.
How do you prove each I2C read returned two bytes before converting? #
Check the return of Wire.requestFrom(Addr, 2) and accept the reading only when Wire.available() reports 2; the sketch converts a local array named data that stays uninitialized when the read fails, so a broken bus yields a plausible-looking number instead of an error.
The sketch sends command 0xF5 for humidity and 0xF3 for temperature to address 0x40, waits out each no-hold measurement, then requests 2 bytes. The byte-count check exists, but the conversion sits outside it: a failed humidity read converts undefined contents, and a failed temperature read converts the humidity bytes still sitting in data. Wire.endTransmission() is unchecked too, so a sensor that never acknowledged the command still reaches the conversion code.
| Check | Value in the sketch | What confirms it |
|---|---|---|
| I2C address | 0x40 | the intended sensor acknowledges at that address |
| Humidity command | 0xF5, no-hold master | 2 bytes come back |
| Temperature command | 0xF3, no-hold master | 2 bytes come back |
| Bytes per measurement | 2, MSB first | Wire.available() equals 2 before conversion |
| Serial Monitor | 115200 baud | matches Serial.begin(115200) |
Worked example for the temperature conversion, with example byte values: MSB 0x66, LSB 0x60. Raw = 102 * 256 + 96 = 26,208. Celsius = 26,208 * 175.72 / 65,536 - 46.85 = 70.27 - 46.85 = 23.4 °C. Fahrenheit = 23.4 * 1.8 + 32 = 74.2 °F. The humidity conversion works the same way — raw * 125 / 65,536 - 6 gives %RH — behind the same byte-count gate. A read that returns no bytes instead leaves stale contents in place and produces a number that can look just as plausible, which is why the byte count, not the value, is the gate.
Decision: convert only after Wire.endTransmission() succeeds and Wire.requestFrom(Addr, 2) leaves 2 bytes available; on failure, publish nothing and count the failure.
Why does the sampling loop stretch past the 5000 ms interval? #
The sketch samples inside a blocking while (millis() - Timer <= Interval) loop whose passes each wait about 1.8 s, so the window runs roughly 5.4 s before any publish, and a failed broker connection adds a blocking delay(5000) retry that halts sampling entirely.
Each tempTask() pass waits 500 ms after the humidity command, 500 ms after the temperature command and 300 ms at its end, about 1.3 s; with the loop's own delay(500), a pass costs about 1.8 s. The window test only runs between passes, so three passes consume about 5.4 s against the configured Interval of 5000 ms, and the publishes happen once, after the batch. Add the loop's head delay(300) and the dashboard update cadence lands near 5.7 s, longer whenever reconnect() blocks in its retry chain. volatile on the measurement variables changes compiler behavior, not scheduling, and fixes none of this.
Blocking also threatens the session: PubSubClient services the keepalive inside client.loop(), and the default keepalive is 15 s unless you change it, so a loop stuck retrying the broker can hold past it and get dropped.
Replace the batch with elapsed-time scheduling: test millis() - lastSample >= 5000 with unsigned subtraction, which survives the rollover near 49.7 days, take one sample, publish it once, and call client.loop() on every pass of loop(). Schedule reconnect attempts instead of spinning inside reconnect(). A board that comes back online but then goes quiet is a different fault — the article on an MQTT client that reconnects but then publishes nothing walks that path.
Decision: one verified sample published once per 5000 ms interval, with client.loop() called between samples; if the dashboard then lags the print by about one interval, timing was the fault.
Did the publish actually reach the broker? #
Every Serial.print in the sketch runs before its client.publish(), so a printed value proves nothing about delivery; capture the Boolean return of each publish, log client.state() when client.connect() fails, and watch the same topics from a second subscriber to confirm the payload left the device.
client.publish() returns false when the client is not connected or when the payload exceeds the internal buffer — the default 256-byte limit, irrelevant here because these payloads are a few bytes, but relevant the day you publish JSON batches. Record three things per attempt:
- the Boolean return of every
client.publish()call, - the
client.state()value printed whenclient.connect()fails, - the payload a second MQTT-in subscriber receives on the same broker.
client.state() returns documented values: -4 connect timed out, -3 connection lost, -2 the server never answered the connect attempt, -1 disconnected cleanly, 0 connected, plus the broker's refusal codes, of which 3 means server unavailable and 5 means not authorized. Check them against the documentation for your installed PubSubClient version, because the meanings are versioned with the library.
The independent delivery check is a second subscriber: an MQTT-in node on the affected topic with a debug node beside the dashboard, compared at the same timestamp. If the debug panel shows nothing at all rather than an old number, that is missing data, not staleness — the walkthrough on fixing MQTT sensor data missing in Node-RED covers that fault.
Decision: the device is cleared when a publish returns true and the second subscriber logs the identical payload string; anything else puts the fault on the connection or the broker.
Why is a public broker the wrong home for plant sensor topics? #
The sketch points at iot.eclipse.org on port 1883, a shared public sandbox it reaches with a client ID and no credentials, so any other client on that broker can publish to the generic topics Ctemp, Ftemp and humid and overwrite your retained value; run your own broker instead.
On a broker you do not control, a topic name is only yours until someone else types it. Another tenant can interleave readings into your stream or replace the stored retained value, and the exposure cuts both ways — your publishes land where anyone watching can read them. The sketch compounds this with a fixed client ID, ESP8266Client: brokers treat a client ID as unique, so a second board flashed with the same sketch disconnects the first one every time it joins.
Treat the configured hostname as the destination the sketch asks for, not a service you own; public sandboxes come and go without notice. For plant telemetry, run the broker on your own edge box or server, name topics per asset — line1/enclosure/tempC rather than Ctemp — require credentials, and turn on transport security; a Node-RED client still speaking plain MQTT to a broker that now requires TLS gets refused, which the article on Node-RED failing when the broker rejects plain MQTT walks through. One line of safety belongs here: keep anything that can act on the process — writes, commands, interlocks — off this telemetry path entirely.
Decision: own the broker before trusting any number it hands you; a value read from a broker you do not control is unverified by definition.
What is the fastest fix order for a stale dashboard value? #
Work from the broker backwards: clear the retained messages first, because they explain most stale readings within minutes; then add read validation, then make the loop nonblocking, then move to your own broker — each step is one code change and one dashboard reload to verify.
- Publish a zero-length payload to Ctemp, Ftemp and humid with retain still set to delete each stored message, then set retain false in the three
client.publish()calls and redeploy. - Gate every conversion on the byte count: convert only when
Wire.endTransmission()succeeds andWire.requestFrom(Addr, 2)leaves 2 bytes available. - Replace the sampling batch and the blocking reconnect with elapsed-time scheduling, publish one verified sample per 5000 ms interval, and call
client.loop()on every pass ofloop(). - Log the
client.publish()return and theclient.state()value on every failure, with timestamps. - Move the topics to a broker you operate, with per-device client IDs, credentials and transport security, and rename them per asset.
Verify in the order the faults sit: after step 1 the dashboard should track the Serial Monitor within one interval; step 2 removes the plausible-but-wrong numbers; step 3 makes the cadence match the interval; step 5 puts the stream under your control.
Decision: if staleness survives all five steps, the remaining suspect is the dashboard node itself — a widget with its own range or smoothing settings — and comparing the debug payload against the widget at the same timestamp settles it in one reload.
Questions asked
What does publishing an empty payload with the retain flag do?
MQTT defines a zero-length payload published with the retain flag set as the way to delete the stored retained message for that topic: the broker keeps no value, and a new subscriber waits for the next live publish. Publishing an empty payload with the retain flag cleared does nothing to storage. After you clear Ctemp, Ftemp and humid once, the next live sample is the only thing a reconnecting dashboard can receive.
Why does the broker drop my board when a second one joins?
The sketch gives every board the same client identifier, ESP8266Client. A broker treats that identifier as unique: when a second device connects with it, the broker closes the first session, so the boards knock each other offline and readings look stale or missing. Build a distinct identifier for each device, for example by appending the last bytes of the module's MAC address, and redeploy.
Does the retain flag explain a value that is wrong by a constant scale?
No. Retention, blocked loops and connection faults deliver old, delayed or duplicate numbers; none of them rescales a value. A repeatable scale or offset error points at the conversion constants in the sketch or at a dashboard node applying its own range mapping, so compare the raw payload string in the debug panel against the printed Serial Monitor value before you touch the broker.
Which client.state() value means the broker refused the connection?
On PubSubClient, state 3 means the broker reported itself unavailable, and state 5 means it rejected the connection as unauthorized, which is what you see once your own broker requires credentials the sketch does not send. A state of -2 means the connect attempt got no response, usually a wrong host or port. Check the meanings against the documentation for the installed PubSubClient version.
Can Node-RED show me the retained flag on an incoming message?
Yes. Set a debug node to display the complete msg object: Node-RED exposes msg.retain, which is true when the broker delivered the stored retained message rather than a live publish. Connect an MQTT-in node on the affected topic, watch the first message after the connection opens, and a true value there confirms the stale number arrived from broker storage, not from the sensor.