Skip to content
Tactiverge

Non-blocking timing and timer wrap-around

Why delay functions freeze the whole program, how to schedule several tasks by checking elapsed time, and how unsigned arithmetic handles timer wrap-around correctly.

Lesson 5 of 6 · 30 min · Self-paced · Free

The problem with waiting

A robot needs to blink a status light every half second, read its distance sensor every 10 ms and check its emergency-stop button constantly. The beginner's blink program from the GPIO lesson used delay_ms(500). During that half second the CPU does nothing else: it reads no sensors and does not notice the stop button. One blocking delay can make the whole robot deaf. This lesson replaces waiting with checking the time, the single most useful pattern in super-loop firmware.

Blocking versus non-blocking

A blocking call does not return until its job is finished. delay_ms(500) is the extreme case: it spends 500 ms counting.

A non-blocking approach asks, on every pass of the loop, "has enough time passed yet?" If yes, it does the job and notes the time. If no, it moves on immediately. Each check takes microseconds, so the loop keeps spinning and every task gets attention.

To ask that question you need a clock. Most firmware keeps a counter of milliseconds since power-on, incremented by a timer interrupt every 1 ms, as built in the timers lesson. We will call it millis_now(), an illustrative name for whatever your board's library provides. It returns a uint32_t.

The elapsed-time pattern

/* Illustrative only: millis_now, gpio_set_mode, gpio_write and gpio_read
   stand in for your board's library; handle_press is your own code. */
#define LED_PIN    13
#define BUTTON_PIN 2

int main(void) {
    gpio_set_mode(LED_PIN, GPIO_OUTPUT);
    gpio_set_mode(BUTTON_PIN, GPIO_INPUT_PULLUP);
    uint32_t last_blink = millis_now();
    int led = 0;

    while (1) {
        uint32_t now = millis_now();

        if ((uint32_t)(now - last_blink) >= 500) {   /* is it time yet? */
            last_blink += 500;
            led = !led;
            gpio_write(LED_PIN, led);
        }

        if (gpio_read(BUTTON_PIN) == 0) {             /* checked every pass */
            handle_press(now);
        }
    }
}

The LED still blinks every 500 ms, but the button is now checked thousands of times per second. (In real code you would debounce it, as in the microcontrollers module.)

Notice last_blink += 500 rather than last_blink = now. If the loop happens to notice 3 ms late, = now would push every later blink 3 ms later, and small delays would add up into drift. Adding the interval keeps the schedule locked to the original timeline. The trade-off: if the loop were ever stalled for several intervals, += would run the task several times in quick succession to catch up. For blinking that is harmless; for some tasks, = now is the better choice. Decide deliberately.

Several tasks, one loop

Each task gets its own "last run" variable. This portable program simulates two seconds of a loop with a pretend clock that advances 1 ms per pass:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint32_t last_blink = 0, last_sensor = 0;
    int led = 0, blinks = 0, sensor_reads = 0;

    /* Pretend clock: one pass of the loop per millisecond for 2 seconds. */
    for (uint32_t now = 0; now < 2000; now++) {
        if ((uint32_t)(now - last_sensor) >= 10) {   /* every 10 ms */
            last_sensor += 10;
            sensor_reads++;
        }
        if ((uint32_t)(now - last_blink) >= 500) {   /* every 500 ms */
            last_blink += 500;
            led = !led;
            blinks++;
        }
    }
    printf("sensor reads: %d, LED toggles: %d, LED now %s\n",
           sensor_reads, blinks, led ? "on" : "off");
    return 0;
}

Output:

sensor reads: 199, LED toggles: 3, LED now on

Why 199 and not 200? The first read happens at 10 ms, not at 0, and the simulation stops at 1,999 ms, so reads occur at 10, 20, ..., 1,990 ms: 199 of them. Toggles happen at 500, 1,000 and 1,500 ms. Counting exactly like this is how you check timing code.

Wrap-around

A uint32_t holds up to 4,294,967,295. Counting milliseconds, it reaches that after:

4 294 967 296 ms ÷ 1000 ÷ 60 ÷ 60 ÷ 24 ≈ 49.7 days

Then it wraps around to 0, as you saw in the C types lesson. A robot left running for seven weeks will hit this. A 16-bit tick counter wraps after only 65.536 seconds. Code that mishandles the wrap usually passes every test on the bench, then fails in the field.

The good news: unsigned subtraction handles wrap-around automatically. Because unsigned arithmetic works modulo 2^32, now - last gives the true elapsed time even when now has wrapped past zero. The tempting alternative, now >= last + interval, does not. This portable program compares both, with last set 296 ms before the wrap:

#include <stdio.h>
#include <stdint.h>

/* Correct: unsigned subtraction gives elapsed time even across a wrap. */
int is_due_good(uint32_t now, uint32_t last, uint32_t interval) {
    return (uint32_t)(now - last) >= interval;
}

/* Wrong: last + interval can wrap to a small number. */
int is_due_bad(uint32_t now, uint32_t last, uint32_t interval) {
    return now >= last + interval;
}

int main(void) {
    uint32_t last = 4294967000u;     /* 296 ms before the counter wraps */
    uint32_t interval = 500;
    uint32_t times[] = {4294967100u, 4294967295u, 0u, 200u, 204u};
    int n = sizeof times / sizeof times[0];

    for (int i = 0; i < n; i++) {
        uint32_t now = times[i];
        printf("now=%10lu  elapsed=%3lu  good=%d  bad=%d\n",
               (unsigned long)now, (unsigned long)(uint32_t)(now - last),
               is_due_good(now, last, interval), is_due_bad(now, last, interval));
    }
    return 0;
}

Output:

now=4294967100  elapsed=100  good=0  bad=1
now=4294967295  elapsed=295  good=0  bad=1
now=         0  elapsed=296  good=0  bad=0
now=       200  elapsed=496  good=0  bad=0
now=       204  elapsed=500  good=1  bad=1

last + interval = 4,294,967,500, which wraps to 204. So the bad version thinks the task is due when only 100 ms have passed: any huge now is "greater than 204". The good version reports due exactly when 500 ms have elapsed, straight across the wrap. Casting the difference back to the counter's own type matters for smaller types: uint16_t values are promoted to int before subtracting, so without a (uint16_t) cast the difference can come out negative.

Project

Three tasks and a wrap test

Extend the two-task simulation in this lesson:

  1. Add a third task that "prints a status report" every 1,000 ms. Predict how many times each task runs in 5 seconds, then run it and compare.
  2. Start the pretend clock at 4,294,965,000 instead of 0 and run for 5,000 passes, so the counter wraps during the run. Confirm the counts are unchanged.
  3. Change one task to the wrong test, now >= last + interval, and repeat step 2. Describe what goes wrong.
  4. Repeat the wrap test using uint16_t for the clock and timestamps, with and without the (uint16_t) cast on the subtraction. Explain any difference.

This is a software-only activity.

Deliverables

  • Predicted and actual run counts for all three tasks
  • Output showing correct behaviour across the wrap with the good test
  • Output and explanation for the wrong test and for the 16-bit experiment

Knowledge check

Check your understanding

  1. 1. A super-loop blinks an LED with delay_ms(1000) and also checks a stop button. What is the problem?
  2. 2. Roughly how long does a uint32_t millisecond counter take to wrap around?
  3. 3. last = 4,294,967,000, interval = 500 and now = 4,294,967,100 (no wrap yet). Why does now >= last + interval wrongly report the task as due?
  4. 4. Why might you write last += interval instead of last = now after running a periodic task?

Go further