SetSysClockTo72()寄存器写法

system_stm32f10x.c中函数,将系统时钟配置成72M

  1. static void SetSysClockTo72(void)
  2. {
  3. __IO uint32_t StartUpCounter = 0, HSEStatus = 0;
  4. /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
  5. /* Enable HSE */
  6. RCC->CR |= ((uint32_t)RCC_CR_HSEON);
  7. /* Wait till HSE is ready and if Time out is reached exit */
  8. do
  9. {
  10. HSEStatus = RCC->CR & RCC_CR_HSERDY;
  11. StartUpCounter++;
  12. } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
  13. if ((RCC->CR & RCC_CR_HSERDY) != RESET)
  14. {
  15. HSEStatus = (uint32_t)0x01;
  16. }
  17. else
  18. {
  19. HSEStatus = (uint32_t)0x00;
  20. }
  21. if (HSEStatus == (uint32_t)0x01)
  22. {
  23. /* Enable Prefetch Buffer */
  24. FLASH->ACR |= FLASH_ACR_PRFTBE;
  25. /* Flash 2 wait state */
  26. FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
  27. FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;
  28. /* HCLK = SYSCLK */
  29. RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
  30. /* PCLK2 = HCLK */
  31. RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
  32. /* PCLK1 = HCLK */
  33. RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2;
  34. /* PLL configuration: PLLCLK = HSE * 9 = 72 MHz */
  35. RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE |
  36. RCC_CFGR_PLLMULL));
  37. RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMULL9);
  38. /* Enable PLL */
  39. RCC->CR |= RCC_CR_PLLON;
  40. /* Wait till PLL is ready */
  41. while((RCC->CR & RCC_CR_PLLRDY) == 0)
  42. {
  43. }
  44. /* Select PLL as system clock source */
  45. RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
  46. RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
  47. /* Wait till PLL is used as system clock source */
  48. while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08)
  49. {
  50. }
  51. }
  52. else
  53. { /* If HSE fails to start-up, the application will have wrong clock
  54. configuration. User can add here some code to deal with this error */
  55. }
  56. }

上图中,第7行代码 RCC->CR |= ((uint32_t)RCC_CR_HSEON);
查询系统定义,#define RCC_CR_HSEON ((uint32_t)0x00010000) ,发现RCC_CR_HSEON=0x00010000,RCC_CR初始值为0x0000 xx83 , RCC->CR =RCC->CR |=RCC_CR_HSEON=0x0000 xx83 |= 0x0001 0000 = 0x0001 xx83, 将RCC->CR寄存器第16位置1,HSE振荡器开启。

接着,在do-while循环中,HSEStatus = RCC->CR & RCC_CR_HSERDY;
查询系统定义#define RCC_CR_HSERDY ((uint32_t)0x00020000),又上一句将RCC->CR寄存器第16位置1,RCC->CR & RCC_CR_HSERDY=0x0001 xx83 & 0x0002 0000 =0x0000 0000. 则HSEStatus的值始终为0,无法结束while循环。

HSE配置系统时钟

新建.h、.c文件

在user文件夹中,新建rcc文件夹,rcc文件夹中新建.c、.h文件
image.png
打开程序,添加.c、.h文件
防止头文件重复引用,.h文件中添加条件编译
image.png

详解代码部分见玩转sTm32。