Simvik

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 to freq_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 35999

50 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 63999

Learn it first

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

More Timers and PWM problems