Non-blocking blink
Derive an LED state from the current time instead of calling delay. An easy embedded C problem (Timing, interrupts and concurrency), run and graded in the…
easy · Timing, interrupts and concurrency · non-blocking · scheduling
delay() stops everything else the firmware should be doing. A non-blocking design asks, on every pass of the main loop, what the output should be right now.
An LED repeats a pattern of on_ms on followed by off_ms off, starting on at time 0. Return true if it is on at time now_ms. If both durations are 0, return false.
Starter code
bool led_on(uint32_t now_ms, uint32_t on_ms, uint32_t off_ms) {
// Where in the on/off cycle is now_ms?
return false;
}Example tests
During the on phase
printf("%d %d\n", led_on(0, 100, 900), led_on(99, 100, 900));Expected output:
1 1During the off phase
printf("%d %d\n", led_on(100, 100, 900), led_on(999, 100, 900));Expected output:
0 0Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Debounce a button · Accept a new button state only after it has been stable for several samples.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Protect a shared variable · Make a read-modify-write safe from interrupts, and safe to nest.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Driver: measure worst-case time with the cycle counter · Enable the Cortex-M cycle counter and time a function across many runs, wraparound included.
- Smart lock: relock after 30 seconds · Relock automatically, with time arithmetic that survives the millisecond counter wrapping.