Simvik

Configure the PLL

Find PLL divider and multiplier values that give the target clock within the chip's limits. A hard embedded C problem (Boot, vector table and clock…

hard · Boot, vector table and clock bring-up · clocks · pll · stm32

An STM32F4's main PLL makes the system clock from the crystal (HSE):

SYSCLK = HSE / M × N / P

with these limits from the reference manual:

  • M from 2 to 63, and the PLL input HSE / M between 1 and 2 MHz,
  • N from 50 to 432, and the VCO output HSE / M × N between 100 and 432 MHz,
  • P one of 2, 4, 6, 8.

Write pll_find(hse_hz, target_hz, cfg): find values giving exactly the target. Search M from smallest to largest, then N, then P, and return the first match (1), or 0 if none exists. Use 64-bit arithmetic where products can overflow.

Starter code

int pll_find(uint32_t hse_hz, uint32_t target_hz, pll_t *cfg) {
  cfg->m = hse_hz / 1000000u;      // 1 MHz into the PLL
  cfg->p = 2;
  cfg->n = target_hz * 2 / 1000000u;
  return 1;
}

Example tests

168 MHz from an 8 MHz crystal

show(8000000u, 168000000u);

Expected output:

168 MHz from 8 MHz: M=4 N=168 P=2

84 MHz from 25 MHz

show(25000000u, 84000000u);

Expected output:

84 MHz from 25 MHz: M=25 N=168 P=2

Learn it first