In this tutorial, I will share how to generate interrupt every given interval using timer on STM32F4 Discovery board. For example project, we will make orange LED toggle every 500ms interval using TIM2. In the main program we will toggle blue LED every 2500ms (blue LED toggling will not using timer interrupt, but just use delay function).
First, we write code for initialize timer. We will use TIM2. This is the block diagram for configuring the timer clock:
void TIM_INT_Init()
{
// Enable clock for TIM2
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// TIM2 initialization overflow every 500ms
// TIM2 by default has clock of 84MHz
// Here, we must set value of prescaler and period,
// so update event is 0.5Hz or 500ms
// Update Event (Hz) = timer_clock / ((TIM_Prescaler + 1) *
// (TIM_Period + 1))
// Update Event (Hz) = 84MHz / ((4199 + 1) * (9999 + 1)) = 2 Hz
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Prescaler = 4199;
TIM_TimeBaseInitStruct.TIM_Period = 9999;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
// TIM2 initialize
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
// Enable TIM2 interrupt
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
// Start TIM2
TIM_Cmd(TIM2, ENABLE);
// Nested vectored interrupt settings
// TIM2 interrupt is most important (PreemptionPriority and
// SubPriority = 0)
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
}