halstm32f7

HAL_Delay is not working properly with STM32F746-DISCO


When HAL_Delay function is called, the processor (STM32F746NG-DISCO) is stuck in the HAL_delay function. I tried changing the HAL_Delay() function for debugging as below

__weak void HAL_Delay(uint32_t Delay)
{
  uint32_t tickstart = HAL_GetTick();
  uint32_t wait = Delay;

  /* Add a freq to guarantee minimum wait */
  if (wait < HAL_MAX_DELAY)
  {
    wait += (uint32_t)(uwTickFreq);
  }
  uint32_t tickEnd = HAL_GetTick();
  while ((tickEnd - tickstart) < wait)
  {
  }
}

while debugging the variable tickEnd is not updating as shown below. tickEnd not updating

As seen above the tickEnd is always set to <optimized out>. The code is generated using touchGFX and it uses TIM6 for system base clock, initially the application used to run properly, I am not sure about the source of this problem, can someone help me figure it out.

NVIC: NVIC Table


Solution

  • You get tickend value only once. You actually don't do any check whether wait time has passed.

    uint32_t tickEnd = HAL_GetTick();
    while ((tickEnd - tickstart) < wait){}
    

    Imagine tickEnd's HAL_GetTick returns 15, tickstart was 10, wait is 20.You have while((15-10) < 20){}, which will be true forever.

    You need to keep updating tickEnd while you wait.

    while ((HAL_GetTick() - tickstart) < wait){}
    

    You need to keep updating the comparison value until enough time has passed. Note, that it works if and only if the tick counter never overflows. If this isn't a concern (depends on use case and how Tick actually works), you can leave it like this. Otherwise, you'll have to come up with a little workaround to take into account that Wait End Tick can actually be a smaller number than Wait Start Tick.

    You can always do "get current tick, add wait tick amount to that number, get end point, check until current tick is equal exactly that". It will work with overflow, but if your system has interrupts, it can fail miserably if interrupt happens when wait must end. Of course, you can make up a workaround for it as well by having some overflow bool, for instance, or you can process such situations separately. Given it's a small job, we don't practically care about having one extra little function that will keep track of things in case of tick overflow.