Simvik

A 10 ms tick, from the clock tree

Work out the timer's input clock from the clock tree, including the APB timer rule, then set the prescaler and auto-reload for a 10 ms period. A medium…

medium · Reading datasheets and schematics · datasheets · driver · timer · clocks

Working from the Datasheet excerpt below, write:

  • tim3_clock_hz(), which returns TIM3's input clock in Hz, calculated from SYSCLK_HZ, AHB_DIV and APB1_DIV with the clock tree's rules.
  • tick_init(), which starts TIM3 with a counter clock of 100 kHz (a tick every 10 µs) and an update event every 10 ms, and makes the settings take effect from the very first period.

The tests measure the time between update events with the cycle counter.

Datasheet excerpt

Clock tree (reference manual, excerpt)

SYSCLK → AHB prescaler → HCLK → APB1 prescaler → PCLK1 → APB1 peripherals

The timers on APB1 (TIM2 to TIM7) are clocked from PCLK1 as follows:

If the APB1 prescaler is 1, the timer clock is PCLK1. Otherwise, the timer clock is 2 × PCLK1.

This board's clock configuration

SettingValue
SYSCLK4 MHz
AHB prescaler1
APB1 prescaler8

TIM3 registers (reference manual)

OffsetRegisterDescription
0x00CR1bit 0 CEN: counter enable
0x10SRbit 0 UIF: update event. Write 0 to clear, writing 1 has no effect
0x14EGRbit 0 UG: generate an update event, which loads PSC and restarts the count
0x28PSCprescaler: the counter clock is the timer clock / (PSC + 1). Buffered: takes effect at the next update event
0x2CARRauto-reload: the counter runs 0 to ARR, then an update event

Starter code

uint32_t tim3_clock_hz(void) {
  return SYSCLK_HZ / AHB_DIV / APB1_DIV;
}

void tick_init(void) {
  TIM3->PSC = tim3_clock_hz() / 100000u - 1u;
  TIM3->ARR = 1000u - 1u;
  TIM3->CR1 = 1u;
}

Example tests

The timer clock

printf("TIM3 clock %u Hz\n", (unsigned)tim3_clock_hz());

Expected output:

TIM3 clock 1000000 Hz

A 10 ms period

tick_init();
measure();

Expected output:

period 10 ms

Learn it first

More Reading datasheets and schematics problems