cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F103 Timer Interrupt Issue

Praveen Gonsalves
Associate II
Posted on September 07, 2017 at 13:48

Hello, 

I'm using STM32F103RBT6 for my project, I've designed a custom board. 

I'm using cubemx to generate the basic code and Atollic for debugging.

I'm reading the switches using external interrupt. In the external interrupt call back, I'm starting a timer. 

In the timer interrupt handler, I'm doing some work. 

I've kept the timer timeout period to 2 seconds. 

My problem is whenever the code is started to run for the first time and when I press the switch, the code immediately  goes to the timer interrupt handler. This happens only once for the first time. After this, whenever I press the switch, code goes to the timer interrupt in 2 seconds which is correct. 

Why does it go immediately goes to the interrupt handler for the first time and then works fine thereafter??

I've attached the c file for reference. 

Is there any changes to be made??

Please suggest.

Regards

Praveen

#cubemx-project #mcu #stm #stm32f103
5 REPLIES 5
BG1
Senior
Posted on April 30, 2018 at 19:15

I exactly have the same issue .. When I set the TIM_CEN bit , MCU immediately goes to the interrupt routine ,even though the overflow hasn't occured yet ..But for the next timer stopping and startings , it doesn't give me a problem .. An answer would be appreciated so much ..

Posted on April 30, 2018 at 19:44

Check TIM_SR after setting the timer up. It's probably nonzero; if so, clear it.

JW

Posted on April 30, 2018 at 19:47

I did ... But still no luck ..

BG1
Senior
Posted on May 01, 2018 at 12:51

Well , I gave it a try by forcing the software in a different way ..Here is the Timer_Config function I use to configure the timer ..And now it works as I expect ...

/*¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨*/

void Tim1_Config(void)

{

TIM1->ARR=7199; //Freq

TIM1->PSC=499; //50 mSec Interrupt Period

TIM1->CR1=(uint16_t)0x0000;

TIM1_UIE=1;

NVIC_SetPriority(TIM1_UP_IRQn,1);

while(TIM1_UIF)

TIM1_UIF=0; //Clear TIM1_UIF

TIM1_CEN=1; //Start TIM1

while(!TIM1_UIF)

__NOP(); //Wait till TIM3_UIF goes high

while(TIM1_CEN)

TIM1_CEN=0; //Stop the TIM3

while(TIM1_UIF)

TIM1_UIF=0; //ClearArray TIM3_UIF

while(NVIC_GetPendingIRQ(TIM1_UP_IRQn)) //Clear pending interrupt flag

NVIC_ClearPendingIRQ(TIM1_UP_IRQn);

NVIC_EnableIRQ(TIM1_UP_IRQn); //Now it is safe to enable the timer;

}

/*¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨*/
Posted on May 01, 2018 at 21:22

Nice, but a bit more complicated than needed:

- you don't need to run the timer until update (in order to 'activate' the prescaler); you can force update by setting TIMx_EGR.UG

- if you don't enable the update interrupt in DIER (that's presumably what you do by TIM1_UIE=1;) before the forced update, but only after the update and after the SR has been cleared (TIM1_UIF=0;), you don't need to clear the pending interrupt flag by NVIC_ClearPendingIRQ().

JW