# What is the difference between IQRn 0 and IRQn 1?

I am using STM32CubeMX to program my chip. Essentially I have a timer that i am trying to set to one ms, and every time that timer reaches a ms I want to toggle a pin. My question is that does it matter if my code goes in the IQRn 0 or IRQn 1 section of the TIM2_IRQHandler?

void TIM2_IRQHandler(void)
{
/* USER CODE BEGIN TIM2_IRQn 0 */

/* USER CODE END TIM2_IRQn 0 */
HAL_TIM_IRQHandler(&htim2);
/* USER CODE BEGIN TIM2_IRQn 1 */
if(toggle_pin == 0)
{
HAL_GPIO_WritePin(TEST_PIN_GPIO_Port, TEST_PIN_Pin, GPIO_PIN_SET);
toggle_pin = 1;
}
else
{
HAL_GPIO_WritePin(TEST_PIN_GPIO_Port, TEST_PIN_Pin, GPIO_PIN_RESET);
toggle_pin = 0;
}
/* USER CODE END TIM2_IRQn 1 */
}

• The 0 and 1 are just labels for the 0th and 1st 'USER CODE' sections in the TIM2 Handler. Where you put your code depends on whether you want it to execute before or after the generic HAL_TIM_IRQHandler function. – brhans Jun 18 '19 at 13:40

It shouldn't matter much, at least in this case.

Looks like the HAL library's handler HAL_TIM_IRQHandler calls all the capture callbacks you've registered and resets your timer's interrupt flag. If you don't use them, or don't care about the order in which they are executed with respect to your pin toggle, you can use either one.

The difference could be significant if your interrupt handler took a very long time to finish. If so, you could decide to clear the flag first in order not to lose the next event, etc.

Observations:

• You could use HAL_GPIO_TogglePin(TEST_PIN_GPIO_Port, TEST_PIN_Pin); so you don't have to remember its last state.
• Also, I believe the HAL library uses SysTick with a period of 1ms. You could maybe use that instead of a separate timer.

If you are not using the timer for anything else, then it does not really matter. Of course, if it is put in the first block instead of the second, it will be executed a few cycles earlier.

If you plan to use this timer for anything else as well (although I wouldn't use HAL functions for anything where timing is critical), then TIM2_IRQHandler() is not the right place for your code. HAL_TIM_IRQHandler() would sort out what kind of timer interrupt has occured, and call the appropriate callback function, in your case it'd be HAL_TIM_PeriodElapsedCallback(), that's where you put the code to be executed when the timer has reached the limit.

• Thank you this helps a lot. I'm struggling to find where HAL_TIM_PeriodElapsedCallback(), is – user9964422 Jun 18 '19 at 14:16
• It's declared in stm32*_hal_tim.h and implemented as a weak stub in stm32*xx_hal_tim.c (file names depen on the MCU series). The weak definition means that you are supposed to implement a replacement in your program, that would override the weak function. Just create a function with the name, and put your pin toggling code in there. – followed Monica to Codidact Jun 18 '19 at 14:46