Skip to main content
Explorer
May 13, 2024
Solved

unstable custom delay function (STM32 & STM32CubeIde)

  • May 13, 2024
  • 5 replies
  • 5179 views

 

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.
    Best answer by Radosław

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

    5 replies

    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) { };
    }
    LadyMtAuthor
    Explorer
    May 13, 2024

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

    why timer 3 and not timer 2?

     

    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 ... ?
    Visitor II
    May 13, 2024

    Default promotion to  INT.

     

    LadyMtAuthor
    Explorer
    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.

    Visitor II
    May 13, 2024

    AGAIN  propotion to int

     

    Test your conditions

    LadyMtAuthor
    Explorer
    May 13, 2024

     

    Visitor II
    May 13, 2024
    while (((uint32_t)(__HAL_TIM_GET_COUNTER(&htim2) - start_count)) < delayus) {
    
     }

     

    and ARR of timer must be 0xFFFFFFFF

    Visitor II
    May 13, 2024

    again  promotion to int

    Visitor II
    May 13, 2024

    Promotion to int and

     

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

     

    LadyMtAuthor
    Explorer
    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