Skip to main content
Explorer II
April 30, 2025
Solved

First call of timer expires immediately

  • April 30, 2025
  • 1 reply
  • 301 views

Hi,

I am trying to check if a button is pressed for 3s continuously using a timer which is started through an interrupt. The code for the same is attached below. The issue I am facing is the interrupt is immediately called when I press the button after reset, but it works fine for the consecutive times. 

void EXTI1_IRQHandler(void) {

	if (__HAL_GPIO_EXTI_GET_IT(RESET_Pin) != RESET) {
		__HAL_GPIO_EXTI_CLEAR_IT(RESET_Pin); // Clear the interrupt flag

		if( HAL_GPIO_ReadPin(RESET_GPIO_Port, RESET_Pin) == 0){ //FALLING Edge
			HAL_TIM_Base_Stop_IT(&htim2);
		}else{ //RISING EDGE
			if(!(TIM2->CR1 & TIM_CR1_CEN)){
				__HAL_TIM_SET_COUNTER(&htim2, 0);
				HAL_TIM_Base_Start_IT(&htim2);
			}
		}
	}
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
 /* USER CODE BEGIN Callback 0 */

 /* USER CODE END Callback 0 */
 if (htim->Instance == TIM8) {
 HAL_IncTick();
 }
 /* USER CODE BEGIN Callback 1 */
	if(htim->Instance == TIM2){
		HAL_TIM_Base_Stop_IT(htim);
		osSemaphoreRelease(task_semaphore);
		return;
	}
 /* USER CODE END Callback 1 */
}

 

Things I have already tried:

  • Set the counter to zero at the when initializing it.
  • Calling stop before starting the timer

 

Thanks in advance!

    This topic has been closed for replies.
    Best answer by TDK

    Timer ARR and PSC are preloaded. Generate an update event after you change them and clear the UIF flag.

    1 reply

    TDKAnswer
    Super User
    April 30, 2025

    Timer ARR and PSC are preloaded. Generate an update event after you change them and clear the UIF flag.