cancel
Showing results for 
Search instead for 
Did you mean: 

What is accurate way of generete microsecond delay function without systick timer ?

hazall
Associate III

Here is my code, but its not working correctly

 
void DelayMicros(uint32_t micros) {
	
	   uint32_t multiplier;
     multiplier = SystemCoreClock / 4000000;
 
    micros = micros * multiplier - 10;
    /* 4 cycles for one loop */
    while (micros--);
}
 

5 REPLIES 5
RomainR.
ST Employee

Hello @hazall (Community Member)

Using a GP Timer:

https://community.st.com/s/question/0D50X0000A7UdMjSQK/how-to-correctly-set-up-a-micro-second-timer

Using DWT (only for STM32 with ARM M3/M4/M7/M33 cpu)

https://community.st.com/s/question/0D50X0000BGkxmCSQR/stm32l462-delay-in-a-microsecondus

Regards,

romain.

In order to give better visibility on the answered topics, please click on 'Select as Best' on the reply which solved your issue or answered your question. See also 'Best Answers'

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.

TDK
Guru

You can't count on the loop taking 4 ticks per cycle. The compiler can optimize it out entirely. You can define the loop variable as volatile, in which case the compiler can't optimize it out, but you still cannot guarantee 4 ticks/cycle in general. Using a timer seems best, there are usually more than enough to go around.

If you feel a post has answered your question, please click "Accept as Solution".
Piranha
Chief II

A busy loop delay can be accurate only when written with assembly. And even then an interrupt can happen and f*ck up the accuracy severely.

Use a TIM clocking faster, in free run, without interrupts and check the CNT register, delta that and compare.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
S.Ma
Principal

As said, debug cycle counter seems nice for microseconf delays.

On cortex M0 STM32, I use a LPTIM for it. Can generate an interrupt if later on the core "sleeps' to save a bit more power.