cancel
Showing results for 
Search instead for 
Did you mean: 

unstable custom delay function (STM32 & STM32CubeIde)

LadyMt
Associate III

 

Hello,

I have a small problem when using a custom delay function as follows :

 

void delay_us(uint32_t delayus) {

uint32_t start_count = __HAL_TIM_GET_COUNTER(&htim2);

while ((__HAL_TIM_GET_COUNTER(&htim2) - start_count) < delayus) {

 }
}

 

 The attached image shows the configuration of timer 2.

This delay function should allow me to generate short pulses. except that sometimes it does and sometimes nothing happens when I use it. I don't know what the problem is. Could you please help me?

 

1 ACCEPTED SOLUTION

Accepted Solutions

Interrupt  can be a reason for longer delay, or hal funtion do something 

View solution in original post

18 REPLIES 18
AScha.3
Chief III

Hi,

you should not use some HAL lib calls , if you expect "us" timing, HAL might need 1 us itself .

And why on 32 bit counter ? need more than 60ms delay ? then use HAL_delay () .

I would try : (on TIM3)

void delay_us(uint32_t delayus) 
{
  TIM3->CNT = 0x0000 ; // start_count 
  while ((TIM3->CNT) < delayus) { };
}
If you feel a post has answered your question, please click "Accept as Solution".
Radosław
Senior II

Default promotion to  INT.

 

the 32 bit counter was in the tutorial I followed on youtube.

why timer 3 and not timer 2?

 

I'm starting out in stm32 and unfortunately I don't understand what you're trying to point out. Could you be clearer? Please.


@LadyMt wrote:

 the tutorial I followed on youtube.


Please give a link to that tutorial

 


@LadyMt wrote:

sometimes it does and sometimes nothing happens when I use it. 


What do you mean by, "nothing happens"?

  • There is no delay?
  • Your system hangs?
  • other ... ?

If I try what you suggest, I get stuck in the while loop.

Would you know why?

Radosław
Senior II

AGAIN  propotion to int

 

Test your conditions


@Andrew Neil wrote:

@LadyMt wrote:

 the tutorial I followed on youtube.


Please give a link to that tutorial


I can't find the video exactly. But I can show you another similar video that I also watched. : How to create delay in nano/micro seconds using timers in stm32 (youtube.com)

 



@LadyMt wrote:

sometimes it does and sometimes nothing happens when I use it. 


What do you mean by, "nothing happens"?

  • There is no delay?
  • Your system hangs?
  • other ... ?

What I mean by "nothing happens" is that there are no delays.
I check this on an oscilloscope.

Did you start the timer , before using it ?

 HAL_TIM_Base_Start(&htim3);
If you feel a post has answered your question, please click "Accept as Solution".