2026-04-15 9:31 AM - last edited on 2026-04-15 10:19 AM by Andrew Neil
Hello,
I am using HAL2 and wrote the basic code below:
while (1) {
HAL_GPIO_TogglePin(LD1_PORT, LD1_PIN);
HAL_Delay(1);
}
I looked at the pin with an oscilloscope and I see that the signal stays 2ms low and 2ms high. If I change the code to HAL_Delay(0) I get a signal that stays low 1ms and high 1ms. It's as if the delay is actually the HAL_Delay parameter plus 1ms.
Any explanation?
-Gil
Solved! Go to Solution.
2026-04-15 9:54 AM - edited 2026-04-15 9:56 AM
> It's as if the delay is actually the HAL_Delay parameter plus 1ms.
That's exactly what it does here. Since the tick resolution is 1ms. it needs to have a buffer of 1ms to guarantee the minimum wait time. The argument is the minimum delay.
HAL_Delay(1) will delay between 1-2 ms. If you call it repeatedly in a tight loop, it will delay exactly 2ms on average.
If you need more precision, consider overloading HAL_Delay with your own more precise code. Using a TIM or the DWT->CYCCNT is popular.
2026-04-15 9:37 AM
Have you checked that your system clock is actually what you expect ?
eg, by routing to MCO.
2026-04-15 9:50 AM - edited 2026-04-15 9:51 AM
So try some delays significantly longer than 1ms ...
2026-04-15 9:54 AM - edited 2026-04-15 9:56 AM
> It's as if the delay is actually the HAL_Delay parameter plus 1ms.
That's exactly what it does here. Since the tick resolution is 1ms. it needs to have a buffer of 1ms to guarantee the minimum wait time. The argument is the minimum delay.
HAL_Delay(1) will delay between 1-2 ms. If you call it repeatedly in a tight loop, it will delay exactly 2ms on average.
If you need more precision, consider overloading HAL_Delay with your own more precise code. Using a TIM or the DWT->CYCCNT is popular.