2024-01-27 01:54 AM
Hello,
I'm studing timer, and I wanna raise an interrupt every second using the Timer1.
I write this code in main:
rcc->APBENR2 |= RCC_APBENR2_TIM1EN_Msk; //Enable Timer1 clock
timer->CNT = 0;
timer->ARR = 1000;// up to 1000
timer->PSC |= 16000 - 1;//actual MPU frequency: 16MHz
timer->EGR |= TIM_EGR_UG_Msk;
timer->DIER |= TIM_DIER_UIE_Msk;//Enable Timer1 interrupt
NVIC_SetPriority(TIM1_BRK_UP_TRG_COM_IRQn , 0x01);
NVIC_EnableIRQ(TIM1_BRK_UP_TRG_COM_IRQn);
timer->CR1 |= TIM_CR1_ARPE_Msk | TIM_CR1_CEN_Msk;
And this IRQ handler:
void TIM1_IRQHandler(void)
{
printf("INT\r\n");
if (TIM1->SR & TIM_SR_UIF)
{
printf("INT\r\n");
TIM1->SR &= ~TIM_SR_UIF; // Pulisci il flag di overflow
}
}
The problem is that my code stuck in NVIC_EnableIRQ(TIM1_BRK_UP_TRG_COM_IRQn);
I have no information also in debug...
Could you help me with this interrupt?
Thanks a lot!
Solved! Go to Solution.
2024-01-27 04:07 AM - edited 2024-01-27 04:09 AM
What you see is that the interrupt is being handled by the default "weak" handler over and over again. The reason is, that you did not in fact provide your interrupt handler, as the proper hame of handler is not TIM1_IRQHandler(). See the startup code you are using; if it's in CubeIDE, then it's TIM1_BRK_UP_TRG_COM_IRQHandler() (yes that name is - not coincidentally - similar to the symbol TIM1_BRK_UP_TRG_COM_IRQn you use in NVIC_EnableIRQ()).
Remarks:
- as @gbm said above, don't use &= to clear TIMx_SR flags
- don't use |= to set TIMx_EGR flags as TIMx_EGR is write only, again just use timer->EGR = TIM_EGR_UG_Msk;
- if you want 1 second period with 16MHz clock and PSC=16000-1, set ARR=1000-1
JW
2024-01-27 02:51 AM - edited 2024-01-27 03:00 AM
1. Reset the flag in the first instruction under if(), do not use &=
TIM1->SR = ~TIM_SR_UIF;
2. What do you exactly mean by "code is stuck"? Enable the interrupt in NVIC after starting the timer. Otherwise the interrupt is entered before timer is started because you force the update event (which is not needed).
2024-01-27 04:07 AM - edited 2024-01-27 04:09 AM
What you see is that the interrupt is being handled by the default "weak" handler over and over again. The reason is, that you did not in fact provide your interrupt handler, as the proper hame of handler is not TIM1_IRQHandler(). See the startup code you are using; if it's in CubeIDE, then it's TIM1_BRK_UP_TRG_COM_IRQHandler() (yes that name is - not coincidentally - similar to the symbol TIM1_BRK_UP_TRG_COM_IRQn you use in NVIC_EnableIRQ()).
Remarks:
- as @gbm said above, don't use &= to clear TIMx_SR flags
- don't use |= to set TIMx_EGR flags as TIMx_EGR is write only, again just use timer->EGR = TIM_EGR_UG_Msk;
- if you want 1 second period with 16MHz clock and PSC=16000-1, set ARR=1000-1
JW
2024-01-27 07:19 AM
Thanks a lot @gbm and @waclawek.jan, I solve it!