2025-01-12 12:27 AM
I have written the following code snippet to set the system clock to 32MHz.
int main(void)
{
SystemClock_Config();
while(1){}
return 0;
}
void SystemClock_Config(void)
{
RCC->CR |= (1<<16);//HSE clock enable >> High Speed External
while(!(RCC->CR & (1<<17))); //External high-speed clock ready flag
RCC->CR &= ~(1<<24);//PLL OFF
RCC->CFGR &= ~(0xf<<18);
RCC->CFGR |= (0x2<<18); //PLL multiplication facto >> PLL input clock x 4
RCC->CR |= (1<<24); //PLL enable
while(!(RCC->CR & (1<<25))); //PLL clock ready flag
RCC->CFGR |= (1<<1); // System clock Switch >> PLL selected as system clock
while(!(RCC->CFGR & (1<<3))); //System clock switch status >> PLL used as system clock
RCC-> CFGR &= ~(0xf<<4);
RCC-> CFGR |= (0x8<<4); //AHB prescaler >> SYSCLK divided by 2
RCC-> CFGR &= ~(0x7<<11);
RCC-> CFGR |= (0x0<<11); //APB high-speed prescaler (APB2) >> 0xx: HCLK not divided
RCC-> CFGR &= ~(0x7<<8);
RCC-> CFGR |= (0x4<<8);//APB Low-speed prescaler (APB1) >> 100: HCLK divided by 2
RCC-> APB2ENR |= ((1<<2)|(0x1<<0)); //I/O port A clock enable & Alternate function I/O clock enable
//RCC-> APB2ENR |= ((1<<2)); //I/O port A clock enable
RCC-> CFGR &= ~(0xf<<24);
RCC-> CFGR |= (0x4<<24); //Microcontroller clock output >> System clock (SYSCLK) selected
}
But after debugging, as shown in the picture, the PLL value still remains at 9.
Are my settings wrong? Or do I have to meet certain conditions to apply the settings?
why PLL Not change? Please advise. thanks
2025-01-12 01:53 AM - edited 2025-01-12 02:15 AM
1. Use bit names and offsets defined in MCU header instead of magic numbers.
2. Use single assignment to set the value of CFGR. Use of long sequences of meaningless &= |= makes the code much harder to read.
3. When PLL is enabled, writes to CFGR are ignored. Setup all the parameters first, then enable PLL, wait for it to synchronize and switch to it.
4. Check if the SystemInit routine sets the HSE and PLL - it's common case with STM32F103. If so, switch to HSE, disable PLL then setup it PLL by yourself, then enable it and switch to it.
5. Before switching to PLL, set Flash wait states.
Basic F103 clock setup assuming that clock configuration was not altered after reset:
RCC->CR |= RCC_CR_HSEON;
while (~RCC->CR & RCC_CR_HSERDY) ;
RCC->CFGR = RCC_CFGR_HPRE_DIV1 /* HCLK = SYSCLK */
| RCC_CFGR_PPRE2_DIV1 /* PCLK2 = HCLK/1 */
| RCC_CFGR_PPRE1_DIV2 /* PCLK1 = HCLK/2 */
| RCC_CFGR_PLLSRC/*_HSE*/ | RCC_CFGR_PLLMULL9; /* PLL configuration: PLLCLK = HSE * 9 = 72 MHz */
RCC->CR |= RCC_CR_PLLON;
FLASH->ACR |= FLASH_ACR_LATENCY_2;
while(~RCC->CR & RCC_CR_PLLRDY); /* Wait till PLL is ready */
RCC->CFGR |= RCC_CFGR_SW_PLL; /* Select PLL as system clock source */