jwilleke / ArduinoHA-examples

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

Reading of Sensors appear to stop #8

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.

jwilleke commented 4 months ago

In one instance the readings stop at after starting at 11:50 AM and ended at 7:52 AM Which is 3 hours and 2 minutes and 3 hours is 10800 seconds. 2 minutes is 120 seconds. 10800 + 120 = 10920 seconds. 10920 seconds.

jwilleke commented 4 months ago

Code within the "normal loop" function seem to work fine.

Just the code inside the loop which is where the sensors are read stop getting updates.

jwilleke commented 4 months ago

I assume since the MQTT values are retained, then home assistant just repeats the values.

jwilleke commented 4 months ago

The Grow-Tent system uses the same type of connection and it does not seem to have the issue.

Both of these show as updating:

No other readings from the if ((millis() - lastUpdateAt) > THRESHOLD) show from Nutrient-Tank.

All sensors from Grow-Tent show.

jwilleke commented 4 months ago

Restarting the arduino the sensors run for a while.

jwilleke commented 4 months ago

9 is a pull request to maybe fix?