STM32 blinking LED wrong register?

Viewed 689

Has anyone an idea why the code doesn't work?

RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
GPIOB->MODER &= ~(0x3u << 6u);
GPIOB->MODER |= (0x1u << 6u);
for (int i = 0; i < 1000; i++) {
    GPIOB->ODR |= (0x1u << 0x3u);
}

I'm using a STM board (STM32L432KC) which has an integrated LED that is called pin PB3 (Port 26) but after flashing nothing happens. Actually there should shine a LED. Do I use the right register?

2 Answers

You're setting a bit in the ODR but never clearing it, so it won't flash, you will need a delay between on/off transitions to be able to visibly see it flashing.

It's good practice to write to the BSRR register instead of the ODR too where possible, this allows you to avoid read-modify-write cycles.

If that code is your whole main() then you might want to replace the for (int i = 0; i < 1000; i++) with a while(1), you generally don't want to return from main in an embedded context.

This sequence is wrong (I did not check if you use the correct RCC register)

RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
GPIOB->MODER &= ~(0x3u << 6u);

When you enable the peripheral clock you need to readback the value or add some delay your changes to propagate through the bus. I usually use the barrier instruction for that.

RCC->AHBENR |= RCC_AHBENR_GPIOBEN;
__DMB();
GPIOB->MODER &= ~(0x3u << 6u);

If you do not add this delay (or readback) the first opearation will fail as it will be performed on the non clocked GPIO periperal.

enter image description here

Related