Prescaler and auto-reload
Choose PSC and ARR for a 16-bit timer to hit an update frequency. A medium embedded C problem (Timers and PWM), run and graded in the browser.
medium · Timers and PWM · timer · prescaler · overflow
A 16-bit timer counts at clock_hz / (PSC + 1) and raises an update event every ARR + 1 counts. Both registers are 16 bits wide.
Fill in *psc and *arr so the update rate is as close as possible to freq_hz:
- Use the smallest prescaler that lets ARR fit in 16 bits: a smaller prescaler gives finer resolution.
- With that prescaler, choose the number of counts (
ARR + 1) that gets nearest tofreq_hz.
freq_hz is between 1 and clock_hz.
Starter code
void timer_config(uint32_t clock_hz, uint32_t freq_hz, uint16_t *psc, uint16_t *arr) {
*psc = 0;
*arr = (uint16_t)(clock_hz / freq_hz - 1);
}Example tests
1 kHz from 72 MHz
uint16_t p, a;
timer_config(72000000, 1000, &p, &a);
printf("%u %u\n", p, a);Expected output:
1 3599950 Hz servo frame from 16 MHz
uint16_t p, a;
timer_config(16000000, 50, &p, &a);
printf("%u %u\n", p, a);Expected output:
4 63999Learn 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.
- 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.
- Fix: long delays end far too early · Delays over about four seconds come out wrong.
- 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.