My first STM32 code – please criticize me

ccodecortex-mstm32

I have just wrote my first code on STM32 – blinking LED. It combines a fragments from different sources; please criticize me so I can learn how to write proper code and don't learn stupid habits.

#include "stm32f30x.h"

void SysTick_Handler(void);
void TimingDelay_Decrement(void);
void Delay(__IO uint32_t nTime);

static __IO uint32_t TimingDelay;

int main(void)
{
  RCC->AHBENR  |=  ((1UL << 21) );                  // Enable GPIOE clock??
  GPIOE->MODER |= (1 << 2*8);                       // PIN 9 as output

//GPIOE->BSRR = 1 << 9;                             // LED ON
//GPIOE->BSRR = 1 << 9 << 16;                       // LED OFF
//GPIOE->BRR = 1 << 9;                              // LED OFF

    if (SysTick_Config(SystemCoreClock / 1000))
    { 
    /* Capture error */ 
    while (1);
  }

    while(1)
    {
        GPIOE->BSRR = 1 << 8;   
        Delay(50);
        GPIOE->BRR = 1 << 8;
        Delay(50);
    }
}

void SysTick_Handler(void)
{
  TimingDelay_Decrement();
}

void Delay(__IO uint32_t nTime)
{
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

void TimingDelay_Decrement(void)
{
  if (TimingDelay != 0x00)
  { 
    TimingDelay--;
  }

}

Why I have to enable GPIOE clock? And what's the difference between 1UL << 21 and 1 << 21?

Best Answer

On the STM32s, all peripherals are by default disabled and don't get any clock signals. This saves a bunch of power (and forces you to think about interactions between pins as you code). If you want to use GPIOE, you need to tell the STM32 to enable its clock.

1UL << 21 shifts an unsigned long value of 1 21 bits to the left. 1 << 21 shifts some number valued at 1, but it's some default type, which may or may not be unsigned long, and you don't necessarily know how wide your system defaults are. It will vary by platform and compiler. In fact, UL can vary by platform and compiler as well. It is best to use the library typedefs, which are sure things.

(uint32_t)1 << 21 and (uint64_t)1 << 21 are unambiguous.

Related Topic