New: the AI firewall watches the whole platform and explains each incident in plain words. See how it works

Wemos D1 mini keeps dropping MQTT when I read the LDR in a tight loop

Wemos D1 mini keeps dropping MQTT when I read the LDR in a tight loop

Solved 3 3

Light logger for the hallway, Wemos D1 mini with an LDR on A0. I wanted smooth values so the loop reads A0 as fast as it can and keeps a running average, then publishes every 10 s to Hermetry with PubSubClient.

WiFi keeps dropping. client.state() shows -3 (connection lost) a few times an hour, sometimes -2 on reconnect. When I comment out the analogRead loop it stays connected all day. Is the ADC somehow fighting the WiFi?

♥ 0

Try adding delay(1) in the loop?

Ask me about 4–20 mA.
♥ 0

Pretty much, yes. Hit this with a soil sensor last spring.

On the ESP8266 the ADC and the radio share bits of the RF hardware, and calling analogRead() thousands of times a second starves the WiFi stack. It’s a known issue on that core. delay(1) helps a bit because it yields, but you’re still hammering the ADC.

An LDR in a hallway doesn’t change in milliseconds. Read every 100 ms, average ten readings, done:

unsigned long t = 0; uint32_t acc = 0; uint8_t n = 0;
void loop() {
client.loop();
if (millis() - t >= 100) {
t = millis(); acc += analogRead(A0);
if (++n == 10) { lux_raw = acc / 10; acc = 0; n = 0; }
}
}

And if you ever want every sample in Hermetry, don’t publish each one. Collect a minute of them and send one message with an array of {ts, values} records, a message costs the same against the quota whether it holds one reading or fifty.

If it isn't logged, it didn't happen.
Accepted solution♥ 1

Down to one read every 100 ms and it has been connected for two days straight. Michael, delay(1) alone made it drop less, but it still dropped.

♥ 0
Viewing 4 posts – 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.

Join the conversation

Sign in to ask and answer, like helpful posts and mark the reply that solved your problem. Every contribution earns points and levels.

Share