2025-12-20 6:30 PM
I created system_clock_initial function to config my board using PLL as system clock and running at 200MHz and also get APB1 timer at 100Mhz (for TIM5 delay function). See my code below. After that I create delay function from TIM5 and test with build-in LED when I upload my code to board and it begin to run, at beginning of time LED blink faster than delay time(1second) that I specify but after about 30 second LED blink properly with 1 second delay.
What should I fix it?
void system_clock_initial(void)
{
/* Turn ON HSE oscillator */
RCC->CR |= (RCC_CR_HSEON);
while(!(RCC->CR & RCC_CR_HSERDY_Msk)){}
/* Enable Power interface clock */
RCC->APB1ENR |= (RCC_APB1ENR_PWREN);
/* Enable Backup Domain Write Protection for Access Backup RTC & SDRAM */
PWR->CR1 |= (PWR_CR1_DBP);
/* Set flash period to 7 wait state */
FLASH->ACR = (FLASH_ACR_LATENCY_7WS | FLASH_ACR_PRFTEN);
/* PPRE1 Divide by 4 */
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PPRE1_Msk)) | (RCC_CFGR_PPRE1_DIV4);
/* PPRE2 Divide by 2 */
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PPRE2_Msk)) | (RCC_CFGR_PPRE2_DIV2);
/* RTCPRE Divide by 2 */
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_RTCPRE_Msk)) | (25 << RCC_CFGR_RTCPRE_Pos);
/* Turn OFF PLL oscillator to config PLL*/
RCC->CR &= ~(RCC_CR_PLLON);
while((RCC->CR & (RCC_CR_PLLRDY_Msk))){}
/* Select HSE as source for PLL */
RCC->PLLCFGR |= (RCC_PLLCFGR_PLLSRC_HSE);
/* Clear and set PLLM to 25 */
RCC->PLLCFGR = (RCC->PLLCFGR & ~(RCC_PLLCFGR_PLLM_Msk)) | (PLLM_VAL << RCC_PLLCFGR_PLLM_Pos);
/* Clear and set PLLN to 400 */
RCC->PLLCFGR = (RCC->PLLCFGR & ~(RCC_PLLCFGR_PLLN_Msk)) | (PLLN_VAL << RCC_PLLCFGR_PLLN_Pos);
/* Clear and set PLLP divide by 2 */
RCC->PLLCFGR = (RCC->PLLCFGR & ~(RCC_PLLCFGR_PLLP_Msk));
/* Clear and set PLLQ to 9 */
RCC->PLLCFGR = (RCC->PLLCFGR & ~(RCC_PLLCFGR_PLLQ_Msk)) | (PLLQ_VAL << RCC_PLLCFGR_PLLQ_Pos);
/* Turn ON PLL oscillator */
RCC->CR |= (RCC_CR_PLLON);
while((RCC->CR & (RCC_CR_PLLRDY_Msk)) == 0){}
/* Config System Clock Switch as PLL */
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_SW_Msk)) | (RCC_CFGR_SW_PLL);
while((RCC->CFGR & RCC_CFGR_SWS_PLL) == 0){}
}