</>EmbeddedInterview

How is the system clock configured on an MCU?

MediumMicrocontrollers & ARM Cortex-M

Short answer: An MCU has several clock sources: a fast internal RC oscillator (starts quickly, less accurate), an external crystal or oscillator (accurate, needed for USB, CAN, precise UART baud rates), and a 32.768 kHz low-speed crystal for the RTC. A PLL multiplies a source up to the core frequency, and prescalers divide it for the buses and peripherals. When raising the frequency, increase the flash wait states (and the voltage scale, if applicable) before switching to the faster clock.

Typical sequence (STM32-style)

  1. Enable the external oscillator (HSE) and wait for its ready flag (with a timeout and a fallback to the internal oscillator).
  2. Set the regulator voltage scale for the target frequency if the chip requires it.
  3. Configure flash wait states (latency) and enable prefetch/caches for the new frequency.
  4. Configure the PLL (input divider, multiplier, output dividers), enable it, wait for lock.
  5. Set AHB/APB prescalers so buses stay within their maximum frequencies.
  6. Switch the system clock multiplexer to the PLL and wait until the switch is confirmed.
  7. Update SystemCoreClock so SysTick, delays and UART baud calculations use the right value.

Example numbers: 8 MHz HSE ÷ 8 = 1 MHz × 336 = 336 MHz VCO ÷ 2 = 168 MHz SYSCLK (STM32F4), APB1 = 42 MHz, APB2 = 84 MHz.

Why wait states matter: flash access time is fixed (e.g. ~30 ns). At 168 MHz a cycle is 6 ns, so the CPU must wait several cycles per flash read. Too few wait states → the CPU reads garbage → random HardFaults that appear only at high speed or high temperature.

Other points

  • Clock security system (CSS): detects a failed external crystal and switches to the internal oscillator, raising an NMI.
  • Peripheral clocks must be enabled individually (RCC->AHB1ENR |= ...) before accessing peripheral registers, or writes are ignored and reads return 0: a very common bring-up bug.
  • Low power: run slower or from the internal oscillator when possible; power scales roughly with frequency.
  • Accuracy: UART needs roughly ±2% total baud error, USB full-speed ±0.25% (internal RC oscillators often need clock recovery/trim to meet it), CAN about ±0.5% or tighter.