STM32G4 Clock settings

I find the STM32 clock stuff pretty wierd. I have the 16MHz crystal (HSE) on a custom board and the HSI clock is also 16MHz in my SystemClock_Config() I want to switch betrween the two and expect both versions to work interchangably if I only change the source for the DLL as below:

#if 0
// Use HSI
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI ;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
#else
// Use HSE
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
#endif

If do this however, HSI is fine but with HSE, Serial1 fails (the rest of the trivial code works ok). CubeMX supports my expectation that both variants should work. What do I oversee here? BTW: I believe the B-G431B-ESC1 works by default on the HSI clock as well, ignoring the external crystal.

Replying to myself and hopefully for the help of others:
The solution was simple, just adding -D HSE_VALUE=16000000 to the platformio.ini helped. After a remark by @VIPQualityPost I had done that before, but unfortunately in the wrong file (too many projects open…). It makes a difference in this case, because the framework will assume a default of 24MHz if it is not defined. If it will use HSE_VALUE (default: 24000000) or HSI_VALUE (default 16000000) depends on the actual selection of the system clock source. It does check the different options, which of course makes a lot of sense.

1 Like

I don’t know if it’s possible (or good idea) to adjust HSI_VALUE as this is baked into the silicon. In any case great job on getting it working! I was stumped for the longest time on why my PWM frequency did not match what I was setting, and -D HSE_VALUE was what fixed it for me finally. I think my discovery was buried in some old threads though.