Skip to main content
Associate II
May 13, 2024
Solved

unstable custom delay function (STM32 & STM32CubeIde)

 

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?

 

This topic has been closed for replies.
Radosław
RadosławBest answer
Associate II
May 13, 2024

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

18 replies

AScha.3
Super User
May 13, 2024

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 on " Best Answer ".
LadyMtAuthor
Associate II
May 13, 2024

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

why timer 3 and not timer 2?

 

Andrew Neil
Super User
May 13, 2024

@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 ... ?
A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
Radosław
Associate II
May 13, 2024

Default promotion to  INT.

 

LadyMtAuthor
Associate II
May 13, 2024

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

Radosław
Associate II
May 13, 2024

AGAIN  propotion to int

 

Test your conditions

LadyMtAuthor
Associate II
May 13, 2024

 

Radosław
Associate II
May 13, 2024
while (((uint32_t)(__HAL_TIM_GET_COUNTER(&htim2) - start_count)) < delayus) {

 }

 

and ARR of timer must be 0xFFFFFFFF

Radosław
Associate II
May 13, 2024

again  promotion to int

Radosław
Associate II
May 13, 2024

Promotion to int and

 

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

 }

 

LadyMtAuthor
Associate II
May 13, 2024

@Radosław wrote:

Promotion to int and

 

 

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

 }

 

 


Even with this modification it still works randomly