STM32 HAL_Delay TIMER Microcontroller

2.7k Views Asked by At

What is the difference between HAL_Delay() function and an empty for-loop? Timer should create interrupt and switch off LED. If I use HAL_Delay() in interrupt function the result is that LED is off forever:

void TIM6_DAC_IRQHandler() {
     HAL_TIM_IRQHandler(&htim6);
     HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
     HAL_Delay(125);        
 }

But if I use instead:

void  TIM6_DAC_IRQHandler() {
     HAL_TIM_IRQHandler(&htim6); 
     HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, GPIO_PIN_RESET);
     for (int i=0; i<1000000; i++);
}

then LED1, which is always on in main-file, is set off for short time and then on, as I expect. So why the code with HAL_Delay does not work?

1

There are 1 best solutions below

0
On
  1. The rule of thumb: NEVER USE DELAYS in the interrupt handlers.

HAL_Delay uses SysTick interrupt and if the priority of SysTick is lower than the priority of the interrupt in which handler it is called, will end up in the dead loop as SysTick Handler will be never invoked.

empty loop: I would personally advice to use another forms of the loops:

for(volatile count = 0; count < 1000; count++);

or

for(count = 0; count < 1000; count++) asm("");

https://godbolt.org/z/hY117n