main.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* LED blink project for the STM32L031 */
  2. #include "stm32l031xx.h"
  3. volatile unsigned long SysTickCount = 0;
  4. void __attribute__ ((interrupt, used)) SysTick_Handler(void)
  5. {
  6. SysTickCount++;
  7. if ( SysTickCount & 1 )
  8. GPIOA->BSRR = GPIO_BSRR_BS_13; /* atomic set PA13 */
  9. else
  10. GPIOA->BSRR = GPIO_BSRR_BR_13; /* atomic clr PA13 */
  11. }
  12. void setHSIClock()
  13. {
  14. /* test if the current clock source is something else than HSI */
  15. if ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI)
  16. {
  17. /* enable HSI */
  18. RCC->CR |= RCC_CR_HSION;
  19. /* wait until HSI becomes ready */
  20. while ( (RCC->CR & RCC_CR_HSIRDY) == 0 )
  21. ;
  22. /* enable the HSI "divide by 4" bit */
  23. RCC->CR |= (uint32_t)(RCC_CR_HSIDIVEN);
  24. /* wait until the "divide by 4" flag is enabled */
  25. while((RCC->CR & RCC_CR_HSIDIVF) == 0)
  26. ;
  27. /* then use the HSI clock */
  28. RCC->CFGR = (RCC->CFGR & (uint32_t) (~RCC_CFGR_SW)) | RCC_CFGR_SW_HSI;
  29. /* wait until HSI clock is used */
  30. while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI)
  31. ;
  32. }
  33. /* disable PLL */
  34. RCC->CR &= (uint32_t)(~RCC_CR_PLLON);
  35. /* wait until PLL is inactive */
  36. while((RCC->CR & RCC_CR_PLLRDY) != 0)
  37. ;
  38. /* set latency to 1 wait state */
  39. FLASH->ACR |= FLASH_ACR_LATENCY;
  40. /* At this point the HSI runs with 4 MHz */
  41. /* Multiply by 16 device by 2 --> 32 MHz */
  42. RCC->CFGR = (RCC->CFGR & (~(RCC_CFGR_PLLMUL| RCC_CFGR_PLLDIV ))) | (RCC_CFGR_PLLMUL16 | RCC_CFGR_PLLDIV2);
  43. /* enable PLL */
  44. RCC->CR |= RCC_CR_PLLON;
  45. /* wait until the PLL is ready */
  46. while ((RCC->CR & RCC_CR_PLLRDY) == 0)
  47. ;
  48. /* use the PLL has clock source */
  49. RCC->CFGR |= (uint32_t) (RCC_CFGR_SW_PLL);
  50. /* wait until the PLL source is active */
  51. while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL)
  52. ;
  53. }
  54. int main()
  55. {
  56. setHSIClock();
  57. RCC->IOPENR |= RCC_IOPENR_IOPAEN; /* Enable clock for GPIO Port A */
  58. __NOP();
  59. __NOP();
  60. GPIOA->MODER &= ~GPIO_MODER_MODE13; /* clear mode for PA13 */
  61. GPIOA->MODER |= GPIO_MODER_MODE13_0; /* Output mode for PA13 */
  62. GPIOA->OTYPER &= ~GPIO_OTYPER_OT_13; /* no Push/Pull for PA13 */
  63. GPIOA->OSPEEDR &= ~GPIO_OSPEEDER_OSPEED13; /* low speed for PA13 */
  64. GPIOA->PUPDR &= ~GPIO_PUPDR_PUPD13; /* no pullup/pulldown for PA13 */
  65. GPIOA->BSRR = GPIO_BSRR_BR_13; /* atomic clr PA13 */
  66. SysTick->LOAD = 2000*500 - 1;
  67. SysTick->VAL = 0;
  68. SysTick->CTRL = 7; /* enable, generate interrupt (SysTick_Handler), do not divide by 2 */
  69. for(;;)
  70. ;
  71. }