2023-09-01 03:11 AM
Hi, I'm learning how to use timers by following digikey's tutorial : Getting Started with STM32 and Nucleo Part 6: Timers and Timer Interrupts | Digi-Key Electronics - YouTube
However at 9:41 in the video I don't understand the code :
// If enough time has passed (1 second), toggle LED and get new timestamp
if (__HAL_TIM_GET_COUNTER(&htim16) - timer_val >= 10000)
{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
timer_val = __HAL_TIM_GET_COUNTER(&htim16);
}
What does __HAL_TIM_GET_COUNTER(&htim16) really do? Then what the condition if is testing?
Thanks
Solved! Go to Solution.
2023-09-06 12:55 AM
Wow thank you a lot !
2023-09-06 06:13 PM - edited 2023-09-06 06:16 PM
Jan presented this:
(uint16_t)(__HAL_TIM_GET_COUNTER(&htim16) - timer_val) >= 10000
You asked to explain this:
(HAL_TIM_GET_COUNTER(&htim16) - timer_val) >= 10000
There is a critically important difference in these lines... Without the cast in front the code is prone to fail at overflow because of integer promotion. In this particular case the only thing that saves the day is the fact that the TIM_CNT register is actually defined as uint32_t for all timers, including the 16-bit ones. But, if both sides of subtraction would be of an uint16_t type, the subtraction would be done as int (signed 32-bit) type, produce a negative result and the comparison would also be done on a signed int type and fail.