Milliseconds to ticks
Convert a delay in milliseconds to RTOS ticks, rounding up. A medium embedded C problem (Timing, interrupts and concurrency), run and graded in the browser.
medium · Timing, interrupts and concurrency · rtos · rounding · overflow
An RTOS measures delays in ticks. With a tick rate of tick_hz, convert ms milliseconds to ticks, rounding up, so that a delay is never shorter than requested and a non-zero delay is never zero ticks.
The result must be correct for any ms, including values where ms * tick_hz does not fit in 32 bits.
Starter code
uint32_t ms_to_ticks(uint32_t ms, uint32_t tick_hz) {
// ceil(ms * tick_hz / 1000)
return ms * tick_hz / 1000;
}Example tests
One tick per millisecond
printf("%u\n", ms_to_ticks(250, 1000));Expected output:
250Rounds up
printf("%u\n", ms_to_ticks(15, 100));Expected output:
2Learn 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.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- 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.