Set STM32L432KC to 80MHz using CMSIS

If you want to speed up your STM32L432KC to 80MHz, here’s the code to do it:

/* Set the clock to 80MHz
 * 2022-02-19   Started. Works

#include "gpio.h"

uint32_t SystemCoreClock = 80000000;

void SystemClock_Config_Test(void)
        FLASH->ACR |= 4; // Set flash latency to 4. Apparently necessary.
        while(((FLASH->ACR) & 0b111) != 4); // Are we there yet?

        RCC->PLLCFGR = (40<<RCC_PLLCFGR_PLLN_Pos) | RCC_PLLCFGR_PLLSRC_MSI; // Confiure PLL to use MSI, inc freq
        RCC->CR |= RCC_CR_PLLON; // Turn on the PLL.
        while((RCC->CR & RCC_CR_PLLRDY) == 0); // Wait until it is ready. So many steps!
        RCC->CFGR = 0b111; // set PLL as system clock
        while((RCC->CFGR & RCC_CFGR_SWS) == 0); // wait until PLL has been set up

int main (void) 

        while(1) {

It does rely on my out gpio functions to set pins high and low, but you get the idea. I’ve adopted the approach of using the simplest thing that could possibly work.

The basic approach I used was to use CubeIDE and set up a simple project using the LL library. I then carefully replaced those function calls with CMSIS calls, eliminating anything unnecessary.

I ran some experiments. Cube toggled pins about every 600ns with the clock set at 80MHz. The timings remained the same for both Debug and Release mode. If the clock was not set to 80MHz, then the toggling took 12.1us. That’s a world of difference!

I compared it against my CMSIS version. Without setting the clock speed, and just using the mcu at its default, and debarring optimisations (using “O0”), toggling took 14.7us. If I removed the O0 flag, then it took 1us. Setting optimisations to O2 did not speed things up.

If I used the code above, and set optimisation at O2, then the toggling decreased to 250ns. So it’s at least twice as fast as STM’s LL library. Although I’m tempted to pat myself on the back, I suspect that there are tweaks that one could make to bring the Cube down to my own speed. The LL libraries actually seem pretty good to me, and they ought to compile down to simple register calls, like my code does. I haven’t investigated that possibility, though.

The code is specific to the STM32L432KC, so don’t expect it to work beyond that.

About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s