Showing results for 
Search instead for 
Did you mean: 

What other code portion(using code generation) changes apart from SystemClock Config replacement with clock setting changes



I am using STM32CubeMX to generate the code and test some peripherals which runs at different clock speeds(optimally).

Since there is lot of code I have (specific to application) post STM32CubeMX code generation being written I don't want to reinsert my code after I experiment with different clock speed .So what I am doing is generating different SystemClockConfig methods with different clock settings to test the peripherals(mostly I2C ) by just replacing this SystemClockConfig with the newly generated ones.

I want to know is it Ok to do like this.?

I understand in case of SPI there is a change in the prescaler (only one macro) which gets changed or to be changed whenever we change the system clock

Is there any other portion of the code which changes by just changing the Clock Settings(Sys Clock)



ST Employee

Hi @darla14​,

you may want to check our example package X-CUBE-REF-PM which I believe deals with similar problem - several different clock settings are used in one project over time and the SW including com interface must cope with it.

The SystemClockConfig generated by CubeMX works to change from reset value default clock to the intended state, but calling it when the clock is based on PLL and HSE to switch to HSI won't work. CubeMX cannot generate such code. Easiest is to revert to reset values before calling a different SystemClockConfig. Or you can carefully manage the transition in optimal manner, which is not always trivial.

Regarding the peripheral clock - for example I2C can typically use 4 different internal clock to run the com IP. There are handy macros in the HAL to help with that transition.



To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

Hello @JHOUD​ ,

Thanks for the reference project.

But maybe I was not clear in the question, the main motive is to change the system clock from the clock generator GUI and then generate the Code and use only generated SystemClockConfig portion( which I am assuming and also the question of this post is that no other portion of the code other than SystemClockCOnfig changes )



This depends on the clock source of various modules. If a clock source depends on the sysclk, the initialization code fore affected modules may need change (adjust divisors, etc.). If the clock source for a module does not depend on sysclk (for example, mux'ed to HSE, HSI, LSI...) then no change is needed. And for some modules, initialization code is self-adjusting (as for UARTs, IIRC, where you only specify the baudrate).


Starting from STM32L4, most peripherals have a clock mux upfront, so one clocktree is easier to achieve.