Counter/Timer

cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F1 troubles with a timer

Today I'm working on my program and 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.

Thanks all advices.

0 Kudos
Message 1 of 1
(2,788 Views)