cancel
Showing results for 
Search instead for 
Did you mean: 

Why does HAL_Delay(x) produce a delay of x+1 Ms. Or what.....

Sidlauskas.David
Associate II

I built a simple project using CubeMX(V5.2.1) for an STM32F103C8 (Blue Pill) , and compiled with Keil uVision5.

In CubeMX I enabled LSE and HSE, the SWD, and PA9 as a GPIO output. For everything else I used the CubeMX defaults.

I added the following code to main().

 /* USER CODE BEGIN 2 */

volatile char ii=1;

while(1)

{

HAL_GPIO_WritePin (trigger_GPIO_Port, trigger_Pin, GPIO_PIN_SET);

HAL_Delay(ii);

HAL_GPIO_WritePin (trigger_GPIO_Port, trigger_Pin, GPIO_PIN_RESET);

HAL_Delay(100);

}

 /* USER CODE END 2 */

In Operation, the output is set high, HAL_Delay(ii) is called, the output is set low and there is a delay of 100 milliseconds. Looking with a scope I always see an output pulse width of ii+1 milliseconds, for any ii. If I comment out the Hal_Delay(ii) line, the output pulse width drops to 2.5 usec, so its not the loop that's adding the extra millisecond.

So what am I missing here? The HAL manual is pretty clear about HAL_Delay(x) producing a delay of x ms.

Thanks for your help.

Dave

1 REPLY 1

Well you can see the source.

Thing is, the method used the main loop in the delay routine can take approaching 0 ms if it enters just before the SysTick hits.

Realistically if want precision timing you're not using a tick of 1ms. Use something with finer granularity, or use a TIM to do the job at a HW level.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..