2014-03-12 08:05 AM
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 ofuwTick
- variable that is incremented in SysTick interrupt handler.Bug Description:
When the value of variableuwTick
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: ConsideruwTick = 0xFFFF FF00
and
Delay = 0x101Then
: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 haduwTick
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 #spl2014-09-09 09:17 AM
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.2017-03-31 12:40 PM
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.
2017-03-31 12:51 PM
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
2017-03-31 02:59 PM
Good point. Being unsigned, all is well...