Electronic – STM32F4 (Discovery board) universal delay (milisecs) function

cdelayembeddedmicrocontrollerstm32

On the net, I have found following function for delay in miliseconds for STM32F4 (Discovery board MCU:

void delay_us(const uint32_t us)
{
    us*=STM32_DELAY_US_MULT;

    /* fudge for function call overhead */
    //us--;
    asm volatile(" mov r0, %[us] \n\t"
                 "1: subs r0, #1 \n\t"
                 " bhi 1b \n\t"
                 :
                 : [us] "r" (us)
                 : "r0");
}

Inside this function, constant STM32_DELAY_US_MULT is used, but not declared and it does not compile, but this is not current problem. How does one get current STM32F4 clock and set this constant according to it? If I ask in another way, how do I write delay (milisecs) function for STM32F4 proc, that is clock independent?

Best Answer

You could use a timer or the RTC with sub-millisecond accuracy instead. These are a lot more versatile and prevents busy-waiting. They can also be easily configured as busy-waiting by adding an additional while loop when this is needed.

There are existing example code for what you want to achieve. This examples shows how to get the current system clock etc.

If you download: STM32F4 DSP and standard peripherals library

and navigate to:

STM32F4xx_DSP_StdPeriph_Lib_V1.2.0\Project\STM32F4xx_StdPeriph_Examples\SysTick\SysTick_Example\system_stm32f4xx.c

There is a function named: SystemCoreClockUpdate()

This function and the Doxygen style comments above will answer your question.

In my experience with STM32 it is that the standard peripherals library examples usually has the most answers when it comes to configuration. You can also watch the standard peripherals library examples for STM32F1, STM32F2, STM32F3 etc. as well. There are a lot of examples out there. Also try the Keil examples.