jwilleke / ArduinoHA-examples

Various attempts to Connect to home assistant using MQTT
0 stars 0 forks source link

Reading of Sensors appear to stop #9

Closed jwilleke closed 4 months ago

jwilleke commented 4 months ago

The sensors:

((millis() - lastUpdateAt) > THRESHOLD)

Where

When Imonitor MQTT with a broker it appears that they are not read at all?

The expression (millis() - lastUpdateAt) > THRESHOLD in Arduino code typically won't overflow itself, even if millis() overflows. Here's why:

Overflow of millis(): millis() is an unsigned long variable, which on most Arduino boards has a maximum value of 4,294,967,295 milliseconds (approximately 50 days). After reaching this limit, it wraps around to zero and starts counting again.

Subtraction handling overflow: In your code, even if millis() overflows and becomes zero, the subtraction (millis() - lastUpdateAt) usually won't cause an overflow because it considers the relative difference between the two values.

Here's a breakdown of why overflow is avoided:

Assuming overflow: Let's say millis() overflows to zero, and lastUpdateAt has a previous high value (close to the maximum). Subtraction: When you subtract the new millis() (zero) from lastUpdateAt, the result will be a large positive number because lastUpdateAt was much bigger. Comparison: This large positive number is then compared to THRESHOLD. As long as THRESHOLD is a reasonable value (less than the maximum millis() value), the condition (millis() - lastUpdateAt) > THRESHOLD will still evaluate correctly.

It appears the loop

if ((millis() - lastUpdateAt) > THRESHOLD)
{
  ....various code here....
    // reset loop timer
    lastUpdateAt = millis();
}

stops executing the code inside the loop.