cancel
Showing results for 
Search instead for 
Did you mean: 

Init a simple timer, get his counter value, reset it

jean_prieur
Associate III
Posted on November 19, 2013 at 13:08

Hello,

I want to initialize a timer which will serve to count the time between two actions. For example, counting the time between two button press. So the timer have to count in a loop. Each time I press a button I have get the value of the counter timer and reset this counter. Very simple operation. I do not find any example to achieve this... I try several modes but I don't know how to configure the timer (like in capture mode). This is my working code:

TIM_TimeBaseInitTypeDef TIM_InitStruct;
void
TIM_Config(
void
){
/* The timer for the frequency between two button press calculation */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE);
TIM_InitStruct.TIM_Prescaler = 84 - 1; 
// This will configure the clock to 1 MHz
TIM_InitStruct.TIM_CounterMode = TIM_CounterMode_Up; 
// Count-up timer mode
TIM_InitStruct.TIM_Period = 3000000 - 1; 
// This is the value of the loop = 3 seconds
TIM_InitStruct.TIM_ClockDivision = TIM_CKD_DIV1; 
// Divide clock by 1
TIM_InitStruct.TIM_RepetitionCounter = 0; 
// Set to 0, not used
TIM_TimeBaseInit(TIM5, &TIM_InitStruct);
/* TIM5 enable counter */
TIM_Cmd(TIM5, ENABLE);
TIM_ITConfig(TIM5, TIM_IT_CC1, ENABLE); 
// Interrupt config
}
void
EnableTimerInterrupt(
void
)
{
 

 NVIC_InitTypeDef nvicStructure5;
nvicStructure5.NVIC_IRQChannel = TIM5_IRQn;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
nvicStructure5.NVIC_IRQChannelPreemptionPriority = 5;
nvicStructure5.NVIC_IRQChannelSubPriority = 0x00;
nvicStructure5.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicStructure5);
}
/* TIM 5 interrupt : activated each time the counter timer go to 3000000 */
void
TIM5_IRQHandler(
void
){
//if interrupt happens the do this
if
(TIM_GetITStatus(TIM5, TIM_IT_Update) != RESET){
//clear interrupt and start counting again to get precise freq
TIM_ClearITPendingBit(TIM5, TIM_IT_Update);
}
}

What is the best way to know the counter value of TIM5 ? And reset TIM5 ? Thanks !
4 REPLIES 4
Posted on November 19, 2013 at 13:18

x =TIM5->CNT;

TIM5->CNT = 0;
Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
jean_prieur
Associate III
Posted on November 19, 2013 at 15:28

Thanks Clive ! Again you save me...

Posted on November 19, 2013 at 15:45

Should be Update, not CC1

TIM_ITConfig(TIM5, TIM_IT_CC1, ENABLE); 
// Interrupt config

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
jean_prieur
Associate III
Posted on November 20, 2013 at 11:46

Yes, I had noticed this but I forgot to mention it 🙂