cancel
Showing results for 
Search instead for 
Did you mean: 

STM32G030 microsecond delay

sandeep3
Associate II

Hello guys.

 

I am working with STM32G030 MCU for delay in millisecond 

HAL_Delay();

is working fine.

but I want to do a delay in microseconds 

so will you please guide how I can do this?

 

I followed this tutorial but not getting desired result.

https://controllerstech.com/create-1-microsecond-delay-stm32

 

MY MCU operates on 16MHZ 

1 ACCEPTED SOLUTION

Accepted Solutions
TDK
Guru

Set up a 32-bit timer to count at 16 MHz. Then your delay function would look like this:

void DelayUS(uint32_t us) {
    uint32_t start = TIMx->CNT;
    uint32_t duration = us * 16;
    while (TIMx->CNT - start < duration);
}

 The delay will not be exactly 1 us due to overhead, but it will be close. You can get fancy and remove the overhead in the "duration" if desired, but be aware overhead will be dependent on compiler settings.

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

View solution in original post

3 REPLIES 3
TDK
Guru

Set up a 32-bit timer to count at 16 MHz. Then your delay function would look like this:

void DelayUS(uint32_t us) {
    uint32_t start = TIMx->CNT;
    uint32_t duration = us * 16;
    while (TIMx->CNT - start < duration);
}

 The delay will not be exactly 1 us due to overhead, but it will be close. You can get fancy and remove the overhead in the "duration" if desired, but be aware overhead will be dependent on compiler settings.

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

Or a 16-bit one if there are no 32-bit TIM or your given 32-bit STM32

void DelayUS(uint16_t us) {
    uint16_t start = TIMx->CNT;
    uint16_t duration = us * 16;
    while((TIMx->CNT - start) < duration);
}

You could also prescale to 1 MHz if thats easier, but the granularity is rougher. 

You want the TIM to be maximal, and not interrupting. So TIM->ARR = 0xFFFF or 0xFFFFFFFF

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

Don't forget the cast. The code will not fail in this particular case if the register type is uint32_t, but can easily turn into a bug if the register is replaced with a variable of a less than 32-bit size.

 

while((uint16_t)(TIMx->CNT - start) < duration);