emonpi icon indicating copy to clipboard operation
emonpi copied to clipboard

Overflow of "now" variable after 50 days?

Open SeanDS opened this issue 6 years ago • 0 comments

In src.ino, the variable now is set to the result of millis(). The Arduino documentation for this function states:

This number will overflow (go back to zero), after approximately 50 days.

I think this has an effect on the RF reset timeout and sample checks:

if ((now - last_rf_rest) > RF_RESET_PERIOD)
if ((now - last_sample) > TIME_BETWEEN_READINGS)

I think that after now overflows, the checks above will always result in false until now again reaches the time of the last last_rf_rest and last_sample times before the overflow, i.e. around once every 50 days. That means that from power-on, the board will reset the RF module and make samples every RF_RESET_PERIOD and TIME_BETWEEN_READINGS milliseconds, until ~50 days have past, then only make samples and reset the RF module every 50 days.

Maybe I've misunderstood how this works in the C/AVR/Arduino world, but I thought I'd point it out in case this is a bug.

A potential fix could simply be to put this before the two checks above:

  // Check if now has overflowed.
  if (now < last_sample || now < last_rf_rest) {
    // Assume now has overflowed, so reset variables that are checked against now.
    last_rf_rest = 0;
    last_sample = 0;
  }

SeanDS avatar Nov 10 '18 20:11 SeanDS