cancel
Showing results for 
Search instead for 
Did you mean: 

unstable custom delay function (STM32 & STM32CubeIde)

LadyMt
Associate II

 

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?

 

18 REPLIES 18
Radosław
Senior II

again  promotion to int


@AScha.3 wrote:

Did you start the timer , before using it ?

 

 HAL_TIM_Base_Start(&htim3);

 


yes I did

Radosław
Senior II

Promotion to int and

 

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

 }

 

I just tried (on F303 , TIM3 ) : works, as it should do.

+

Did you set counter period (ARR) to something big ? 0xFFFF .

+ counter mode up ?

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

 

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

 }

 

and ARR of timer must be 0xFFFFFFFF


@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


@Radosław wrote:
while (((uint32_t)(__HAL_TIM_GET_COUNTER(&htim2) - start_count)) < delayus) {

 }

 

and ARR of timer must be 0xFFFFFFFF



yes timer ARR is 0xFFFFFFFF

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