Simvik

Fix: long delays end far too early

Delays over about four seconds come out wrong. A medium embedded C problem (Timers and PWM), run and graded in the browser.

medium · Timers and PWM · find-the-bug · overflow · timers

Bug report. Short delays are accurate. But the 5 second watchdog feed interval fires after about 0.7 seconds, and the 10 second sensor warm-up is cut short too. Every delay below about 4.2 seconds is fine.

ms_to_ticks converts a delay in milliseconds to timer ticks. It must be exact for every delay up to one minute (60 000 ms); the result always fits in 32 bits. Find the defect and fix it by changing one line.

Starter code

uint32_t ms_to_ticks(uint32_t ms) {
  return ms * TIMER_HZ / 1000;
}

Example tests

Short and long delays

printf("%u %u %u\n", ms_to_ticks(1), ms_to_ticks(1000), ms_to_ticks(5000));

Expected output:

1000 1000000 5000000

Learn it first

  • Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.

More Timers and PWM problems