cancel
Showing results for 
Search instead for 
Did you mean: 

Delay in us

l90mehdi
Associate II
Posted on April 08, 2016 at 13:17

hi

I am coding with HAL driver.I need delay in us range.but HAL driver can creation delay in ms.

so How can i use HAL Driver in us? 

#hal_delay
13 REPLIES 13
Posted on April 06, 2017 at 19:09

The 32-bit TIM2 of F2/F4 parts is good for this too. You can place TIM2->CCRx triggers down the timeline.

Clock the timer faster than you need as you don't know the phase of the input clock (ie did it just tick, or is it 1us from ticking again at 1MHz)

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
hitesh poshia
Associate II
Posted on June 29, 2017 at 10:01

use DWT counter for generating microsecond delay. you can use this along with HAL library

------------------------------------------------------------------------------------------------------------------------------

__STATIC_INLINE void DWT_Delay_us(volatile uint32_t microseconds)

{

uint32_t clk_cycle_start = DWT->CYCCNT;

/* Go to number of cycles for system */

microseconds *= (HAL_RCC_GetHCLKFreq() / 1000000);

/* Delay till end */

while ((DWT->CYCCNT - clk_cycle_start) < microseconds-15);      // change value of 15 to adjust timing (microseconds-x)

}
Posted on June 29, 2017 at 20:17

 ,

 ,

In a system where you use a fixed frequency I would recommend doing the calculation with the division once, outside the delay function.

Take the subtraction outside of the loop, and don't make microseconds volatile, it is not changing. You probably won't need the fudge factor if you're not calling external maths routines or doing division.

uint32_t DWT_Scale = ,

(HAL_RCC_GetHCLKFreq() / 1000000), // Do this ONCE

♯ define DWT_Fudge 1 // Likely mostly unnecessary, tuning value to account for call and computation overhead

__STATIC_INLINE void DWT_Delay_us(uint32_t microseconds)

 ,

{

uint32_t clk_cycle_start = DWT->,CYCCNT,

uint32_t ticks = (

microseconds * ,

DWT_Scale) - DWT_Fudge, ,

/* Go to number of cycles for system */

while ((DWT->,CYCCNT - clk_cycle_start) <, ticks), ,

/* Delay till end */

 ,

}
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on December 08, 2017 at 17:30

I tried that on an F7 with no luck, after google a bit I found this:

volatile uint32_t *DWT_CONTROL = (uint32_t *) 0xE0001000;
volatile uint32_t *DWT_CYCCNT = (uint32_t *) 0xE0001004;
volatile uint32_t *DEMCR = (uint32_t *) 0xE000EDFC;
volatile uint32_t *LAR = (uint32_t *) 0xE0001FB0; // <-- added lock access register
*DEMCR = *DEMCR | 0x01000000; // enable trace
*LAR = 0xC5ACCE55; // <-- added unlock access to DWT (ITM, etc.)registers 
*DWT_CYCCNT = 0; // clear DWT cycle counter
*DWT_CONTROL = *DWT_CONTROL | 1; // enable DWT cycle counter

Adding this to the init make it work