Simvik

Fix: long measurements come out tiny

A tick count is scaled to microseconds through a product that overflows 32 bits. A medium embedded C problem (Fixed-point and signal processing), run and…

medium · Fixed-point and signal processing · find-the-bug · overflow · uint64 · scaling

Bug report. ticks_to_us(ticks, hz) converts a timer's tick count to microseconds, rounding down. Short pulses are measured correctly, but anything longer than about a minute on the 72 MHz timer comes out far too short, as if the time had wrapped. Fix it by changing one line.

Starter code

uint32_t ticks_to_us(uint32_t ticks, uint32_t hz) {
  return ticks * 1000000u / hz;
}

Example tests

A short pulse, then a minute

printf("%u\n", ticks_to_us(720, 72000000));
printf("%u\n", ticks_to_us(2160000000u, 72000000));

Expected output:

10
30000000

Learn it first

More Fixed-point and signal processing problems