cancel
Showing results for 
Search instead for 
Did you mean: 

[bug report] Bug in HAL (SPL) delay function

amomum
Associate III
Posted on March 12, 2014 at 16:05

Setup:

I've just generated code for stm32f407 using the latest STM32CubeMX. Here's the generated code for delay function in file stm32f4xx_hal.c:

void HAL_Delay(__IO uint32_t Delay)

{

  uint32_t timingdelay;

 

  timingdelay = HAL_GetTick() + Delay;

  while(HAL_GetTick() < timingdelay)

  {

  }

}

It's fairly simple,

HAL_GetTick

returns a value of

uwTick

- variable that is incremented in SysTick interrupt handler.

Bug Description:

When the value of variable

uwTick

becomes large enough (i.e. adding Delay will overflow uint32) delay function will not work correctly, because expression ''

HAL_GetTick() < timingdelay

'' will immediately be false.

That results in no delay at all.

Example:

Consider

uwTick = 0xFFFF FF00

and

Delay = 0x101

Then

:

timingdelay = 0xFFFF FF00 + 0x101 == 0x01

Then

while(HAL_GetTick() < timingdelay)

is

(

0xFFFF FF00

< 0x01 ).

This is already false and while is not executed. No delay is performed!

Comment:

This bug can be real pain, because it will work only when overflow of

uwTick

is near (or delay is really large). If one had

uwTick

incremented every millisecond (seems to me like a reasonable value), bug can accure in about 47 days from reset.

Solution:

That's easy enough:

uint32_t startTime = HAL_GetTick();

while( HAL_GetTick() - startTime <= Delay);

If we compare the differencies between moments of time and Delay - we are okay (as long as Delay is not bigger than

0xFFFF FFFF

, but that's sort of unrealistic and can be guaranteed by assert); overflow will not affect it.

#bug-stm32-timeout-hal_gettick #bug #hal #hoist-by-their-own-petard #spl
13 REPLIES 13
Posted on September 09, 2014 at 18:17

Hi suzuki.isaque,

Yes, the current version of STM32CubeF2, is still containing this limitation. We have already passed it along to our development team. Keep an eye out for the next update!

Regards.

Lyle Pakula
Associate II
Posted on March 31, 2017 at 21:40

The proposed fix is in the newest version of the cube software.  Problem is the proposed fix is still an issue.

If tickstart = 0xFFFF FFF0 (almost at overflow)

delay = 0xFF (delay for 255 ms),

Then (HAL_GetTick() - tickstart) > delay will take almost the full 47 days before it becomes valid (and not 255 ms) after the counter rolls over.

Posted on March 31, 2017 at 21:51

Yeah, this is a thing all over the industry. I figured out that I'd been doing it wrong for years, so I wrote an article about it.

http://embedded.fm/blog/2016/9/26/scheduling-code-on-bare-metal

 

Andrei

Posted on March 31, 2017 at 21:59

Good point.  Being unsigned, all is well...