# STM32F1 troubles with a timer

I'm having some troubles with setting up a 1 second timer on STM32F103 mcu.

I have set Timer 2 to have a prescaler of 1099 and a period of 65514, so I'm expecting to have a 1 second interrupt rate: 72MHz/1099/65514 = 1Hz.

Yet in reality I get the first interrupt before even finishing the timer configuration routine (not a big concern at the moment), the next interrupt occurs after 1000ms as expected, the next interrupt occurs after 322ms, and the next after 32ms and the next after 590ms. (these were measured according to the systick timer which I have running at 1ms).

It seems pretty random, what's going on ?

Here is part of the relevant code:

void RCC_Configuration() {
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA |
RCC_APB2Periph_GPIOB |
RCC_APB2Periph_AFIO  |
RCC_APB2Periph_USART1, ENABLE);

RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM3 |
RCC_APB1Periph_TIM2, ENABLE);
}

void Timer2_4_5_Configuration() {
TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;

TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Prescaler = (1099-1);
TIM_TimeBaseStructure.TIM_Period = (65514-1);

TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

TIM_Cmd(TIM2, ENABLE);
}

void NVIC_Configuration () {
NVIC_InitTypeDef NVIC_InitStructure;

NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

NVIC_Init(&NVIC_InitStructure);
}

void TIM2_IRQHandler() {
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
GPIOA->ODR ^= GPIO_Pin_2;
}


EDIT: I managed to get this to work, I did a silly mistake in the rest of my code. I have used the same pin for something else forgot to comment the line, oopsy.

The led on pin 2 toggles at 1Hz as intended, but a new question arises:

I have set a breakpoint at the pin toggle line in the TIM interrupt handler and it seems it fires up at random times as stated above. But when I remove the breakpoint the led toggles as intended.

What's going on ?

P.S - I'm using CooCox IDE.

• Is your PLL up and running before you start configuring the timer? Do you have valid dividers for AHB, APB and Flash clocks? Apart from that, I would check the ARR and PSC registers if they are not owerwritten by accident. – venny Aug 19 '14 at 21:47
• I'm pretty sure the startup code got that covered. I have checked the ARR and PSC registers and they have the needed value. – Mike Aug 19 '14 at 21:56
• Does your code work in simulator? – venny Aug 20 '14 at 0:59
• I'm using Coocox IDE, it doesn't have a built in simulator. Do you have a recommendation for one ? – Mike Aug 20 '14 at 7:42
• You might want to stop the timer at CPU halt, it is set in DBG->DBGMCU_CR. – venny Aug 20 '14 at 14:03