Simvik

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:

250

Rounds up

printf("%u\n", ms_to_ticks(15, 100));

Expected output:

2

Learn it first

More Timing, interrupts and concurrency problems