Skip to main content
gil_dobjanschi
Associate II
April 15, 2026
Solved

HAL_Delay - out by 1ms ?

  • April 15, 2026
  • 3 replies
  • 156 views

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

Best answer by TDK

> 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.

stm32f4xx-hal-driver/Src/stm32f4xx_hal.c at eaa636c7be367100405b2109023c6dbb12429b98 · STMicroelectronics/stm32f4xx-hal-driver

 

If you need more precision, consider overloading HAL_Delay with your own more precise code. Using a TIM or the DWT->CYCCNT is popular.

3 replies

Andrew Neil
Super User
April 15, 2026

Have you checked that your system clock is actually what you expect ?

eg, by routing to MCO.

 

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
Andrew Neil
Super User
April 15, 2026

Bug HAL_delay() off by 1ms

 

So try some delays significantly longer than 1ms ...

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
TDK
TDKBest answer
Super User
April 15, 2026

> 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.

stm32f4xx-hal-driver/Src/stm32f4xx_hal.c at eaa636c7be367100405b2109023c6dbb12429b98 · STMicroelectronics/stm32f4xx-hal-driver

 

If you need more precision, consider overloading HAL_Delay with your own more precise code. Using a TIM or the DWT->CYCCNT is popular.

"If you feel a post has answered your question, please click ""Accept as Solution""."