cancel
Showing results for 
Search instead for 
Did you mean: 

Delay/Wait function

botmail242
Associate II
Posted on July 26, 2016 at 17:28

I have been using a busy for loop to create my delays, but now I need precision. I want a function that will wait for n microseconds. How should I go about doing this? The Systick timer is not accurate enough (already tried it).

7 REPLIES 7
Posted on July 26, 2016 at 18:05

DWT_CYCCNT you can count off CPU cycles, I've posted examples to the forum.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
botmail242
Associate II
Posted on July 26, 2016 at 20:23

Thank you for pointing me in the right direction!

void
enable_delay(void){
DWT->CYCCNT = 0;
CoreDebug->DEMCR |= 0x01000000;
DWT->CTRL |= 1;
}
void
delay(uint32_t tick){
uint32_t start = DWT->CYCCNT;
uint32_t current = 0;
do{
current = DWT->CYCCNT;
}while((current - start) < tick);
}

matic
Associate III
Posted on July 26, 2016 at 21:23

@Community member: Why do you think that Systick is not accurate enough?

@Clive: Is it allowed to use DWT counter as a regular timer? Does it run with SYSCLK frequency? Is debugging not disturbed by using DWT?

Thanks

botmail242
Associate II
Posted on July 26, 2016 at 21:49

I could only get microsecond accuracy with

SysTick_Config(HAL_RCC_GetHCLKFreq()/1000000);
 HAL_GetTick(); 

And yes it uses the SYSCLK. I was using the default on board clock speed 168 MHz. I don't know how it affects debugging.
Posted on July 26, 2016 at 22:35

SysTick typically clocks at 1/8th CPU speed, is only 24-bit, counts down, usually non-maximal, ... so it sucks the math up.

The DWT unit is on the silicon, you can use it or not, I've not had problems debugging. Clocks at CPU speed, is 32-bit, and counts up, @ 72MHz takes a minute to wrap, is thread/interrupt safe for delay loops. I'd define it as a free running counter rather than a timer, no provision for interrupt.

Fastest 32-bit TIM run half clock speed (typically, on APB1)

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
matic
Associate III
Posted on July 26, 2016 at 23:16

John, I asked about Systick accuracy because I thought that you don't know that it can run with SYSCLK too. You just have to configure that in its CONTROL register and then read its CURRENT register. At 72 MHz it takes approximately 233 ms to wrap around, if RELOAD register is set to full 24-bit.

Thanks Clive for clarification.

Posted on July 26, 2016 at 23:30

The math on it is unduly burdensome, effectively diminishing the granularity, and most people use it for a 1ms / 1 KHz ticker.

An atomic 32-bit counter, pretty hard to fault..

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