Hardware.millis() overflow behavior

Given that hardware.millis() is monotonic except at imp reset or when its signed 32 bits integer value overflows (Becomes negative and start counting back up to zero).
In what cases the while loop in the code below can become an infinite loop?
Maybe @phil , @hugo can shed some light here?

_timer_data_last_ms <- 0;

function _timer_block_ms() {
        /* Blocking, Precision timing (millisecond period) for data acquisition */
        local now = hardware.millis();
        while ((now - _timer_data_last_ms) < 1000) {
            now = hardware.millis();
        }
        _timer_data_last_ms = now;
    }

What do you want this code to do? In cases where hardware.millis() returns a negative integer value and _timer_block_ms is called for the first time, it will block for up to 25 days. If you want the routine to block for 1000ms since the last time it was called, I suggest the following:

_timer_data_last_ms <- null;

function _timer_block_ms() {
        /* Blocking, Precision timing (millisecond period) for data acquisition */
        local now = hardware.millis();
        if (_timer_data_last_ms == null) {
            _timer_data_last_ms = now;
        }
        while ((now - _timer_data_last_ms) < 1000) {
            now = hardware.millis();
        }
        _timer_data_last_ms = now;
    }

Because Squirrel is subject to delays, how precise it is will depend on what else the imp is doing. However, the code will ensure that it blocks for at least 1000ms.
Blocking of Squirrel is really harsh. Have you considered using imp.wakeup()? It a bit coarser, around +/- 20ms
Depending on the type of imp you’re using you might be able to set up a 1000ms PWM signal from one digital output pin wired back into a digital input that triggers a stateChangeCallback

This topic was automatically closed after 60 days. New replies are no longer allowed.