Search code examples
cstm32f4discoverytimedelay

Nucleo STM32F446RE - DELAY function not working


I'm trying to do a simple C program to make LED blinking using the program below:

#include "stm32f4xx.h"

#include "stdint.h"

#include "stdlib.h"

void delayMs(int n);

int main(void) {

RCC->AHB1ENR |= 1; /* enable GPIOA clock */

GPIOA->MODER &= ~0x00000C00; /* clear pin mode */

GPIOA->MODER |= 0x00000400; /* set pin to output mode */

while(1) {

GPIOA->BSRR = 0x00000020; /* turn on LED */

delayMs(500);

GPIOA->BSRR = 0x00200000; /* turn off LED */

delayMs(500);

}

}

void delayMs(int n)

{

int i; for (; n > 0; n--)

for (i = 0; i < 3195; i++) ;

}

I build the code using KEIL uVision IDE with 0 Error and I download it to the nucleo board but the LED doesn't blink. However, in debug mode I succeed to turn ON and off the LED but without delay. I notice that in debug mode I never enter the delay function. Is there any explanation to such issue. I thank you for your help.


Solution

  • This is an optimization of C compiler, which is removing your loop. You can check with debugger, that there will be no assembly code generated for the loop. You either put there __NOP() instruction inside the loop, so there is some code to be executed.

    You can also use HAL_Delay() function.

    These kind of "delay loops" are useful only for some basic testing and they should never be in your final production code. Precise timing should be done with timers and when there is nothing to do for the core, it should be put in sleep mode to save power.