ST MCU clocks can be notoriously difficult to set up. Indeed, a study of the system “clock-tree” is important to understand how the device generates clocks for different subsystems:
As you can see, the clock tree is complex. The input can come from a number of sources, and is then multiplied and divided to generate the system clocks and various bus clocks. To top it off, different ST MCU series have different clock trees, and sometimes even a particular device may have a slightly different clock tree than the other devices in the same series. Furthermore, some peripherals such as USB have clock speed requirements that might limit the choices of the system clock speed.
STM32 devices may use a number of input clocks. Not all input sources are possible in all devices. Consult the device datasheet for detail.
· LSI (typical 32KHz), Low Speed Internal clock, driven by an RC circuit
· LSE (typical 32KHz), Low Speed External clock using an oscillator
· HSI (8 or 16 MHz, depending on the device), High Speed Internal clock, driven by an RC circuit
· HSE (typical 2 MHz to 26 MHz), High Speed External clock using an oscillator
HSE is the preferred source for most accurate timing. Some peripherals may have their own input clock source.
The input clock is usually fed to the PLL (Phase Lock Loop) to derive a high speed (48Mhz for F0xx, 100Mhz for F4xx, and over 200 MHz for F7xx) system clock SYSCLK. SYSCLK drives the CPU and is input to the peripheral buses.
Peripherals (GPIOs, timers, etc.) are attached to the APB (Advanced Peripheral Bus), which is in turn is attached to the AHB (Advanced High-performance Bus). Depending on the STM32 device, there can be one or two APBs. The AHB and APB clocks are called HCLK and PCLK respectively.
HCLK is derived from SYSCLK, and PCLKs are derived from the HCLK. There are optional prescalers (dividers) between the clocks, and each APB has its own prescaler:
SYSCLK – prescaler à HCLK – prescaler à PCLK
There maybe limits on how fast the HCLK and PCLK can run. Refer to the device’s datasheet for detail. The example below shows how to change the APB prescaler.
No wonder then that other than using JSAPI, the easiest way to get the clock set up correctly for an ST MCU is to use ST’s graphical configuration tool CubeMX. With CubeMX, you can specify the input source and the desired output clock behaviors, and the tool does the rest. There are, however, issues with using CubeMX but we will not get into them here .