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 5000000Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Servo pulse width · Turn an angle into the compare value for a hobby servo's pulse.
- Prescaler and auto-reload · Choose PSC and ARR for a 16-bit timer to hit an update frequency.
- Frequency from input capture · Compute a signal's frequency from two capture timestamps on a 16-bit timer.
- Duty cycle from captures · Measure a PWM signal's duty cycle in tenths of a percent.
- Decode a quadrature encoder · Turn A/B channel transitions into +1, -1 or 0 steps with a lookup table.
- Software PWM · Drive four PWM channels from a timer tick on pins without PWM hardware.
- Fan speed from tach pulses · Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls.
- Driver: a millisecond delay on a hardware timer · Program a timer's prescaler and auto-reload, and wait for exactly one period.
- Fix: 100 % brightness still flickers · A duty-cycle conversion uses the auto-reload value instead of the period length.
- Greenhouse: fan speed from temperature · Map a temperature to a PWM duty cycle, without stalling the fan at low speed.
- Robot gripper: servo angle to timer value · Turn a servo angle into the timer's compare value, within the gripper's mechanical limits.