</>EmbeddedInterview

How do you implement a delay without blocking the CPU?

MediumEmbedded C

Short answer: Use a free-running time base (e.g. a 1 ms SysTick counter or a hardware timer) and compare timestamps instead of spinning in a delay loop. Record the start time, return to the main loop, and check later whether the required time has elapsed. Use unsigned arithmetic (now - start) >= interval so the check keeps working when the counter wraps around.

#include <stdbool.h>
#include <stdint.h>

static volatile uint32_t g_ms;              /* incremented in SysTick_Handler */
void SysTick_Handler(void) { g_ms++; }

static inline uint32_t millis(void) { return g_ms; }   /* 32-bit read is atomic on Cortex-M */

typedef struct { uint32_t start, interval; } soft_timer_t;

bool timer_expired(soft_timer_t *t)
{
    if ((uint32_t)(millis() - t->start) >= t->interval) {
        t->start += t->interval;            /* keeps a fixed period without drift */
        return true;
    }
    return false;
}

/* main loop */
soft_timer_t led = { 0, 500 };
for (;;) {
    if (timer_expired(&led)) toggle_led();
    poll_uart();                            /* other work keeps running */
}

Why unsigned subtraction works across wrap-around: if start = 0xFFFFFFF0 and the counter wraps to now = 0x00000010, then now - start in 32-bit unsigned arithmetic is 0x20 = 32 ms, which is correct. The broken form if (now >= start + 500) fails because start + 500 wraps to a small number and the condition becomes true immediately (or never). The difference must be compared, not the absolute times. A 32-bit millisecond counter wraps every 49.7 days, which is exactly when long-running devices fail with the broken form.

Other non-blocking approaches

  • Hardware timer interrupt or one-shot timer that sets a flag or calls a callback.
  • State machines where each state records when it was entered and moves on when a timeout passes.
  • RTOS: vTaskDelay()/vTaskDelayUntil() block only the calling task; other tasks run (this is "blocking" for the task but not for the CPU).
  • Low power: if nothing else needs doing, sleep (__WFI()) until the next timer interrupt instead of busy-polling.

When short busy-wait delays are fine: a few microseconds required by hardware (e.g. a 10 µs reset pulse) can use a cycle-counter loop (DWT->CYCCNT on Cortex-M3+), but not with a plain for loop, which the optimiser may delete and whose timing depends on clock speed and flash wait states.