jeudi 2 janvier 2014

Timer with STM32F4

Hello,
This time I'll give you a short tutorial about how to use timers with the STM32.
Timers are very useful when it comes to make a precise period of time independantly from your main loop execution.


The stm32F4 has many timers each one with a specific need. I'm just going to use the Timer 2 to make an interruption each 0.25 sec.
I use a C# program to calculate what values to put in the prescaler and the periode to get my required interruption time.
https://www.mediafire.com/?bq21q5qd7frcvba

The code has comments in it but if there is something that is not clear explained in the comments below, I'll be happy to answer.


void TIM2_IRQHandler(void){
 static short i = 0;
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
 GPIO_WriteBit(GPIOD,GPIO_Pin_13,i++);
GPIO_ToggleBits(GPIOD, GPIO_Pin_14);
}
}

void INTTIM_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
/* Enable the TIM2 gloabal Interrupt */
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);
 
/* TIM2 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* Time base configuration */

TIM_TimeBaseStructure.TIM_Period = 1000000 - 1; // 1 MHz down to 1 KHz (1 ms)
TIM_TimeBaseStructure.TIM_Prescaler = 43- 1; // 24 MHz Clock down to 1 MHz (adjust per your clock)
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
/* TIM IT enable */
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
/* TIM2 enable counter */
TIM_Cmd(TIM2, ENABLE);
}

int main(void)
{

 STM_EVAL_LEDInit(LED3);
 STM_EVAL_LEDInit(LED4);
 STM_EVAL_LEDInit(LED5);
 STM_EVAL_LEDInit(LED6); 
 INTTIM_Config();
 while(1);
}

1 commentaire:

  1. Hi, in C# aplication you have:
    Tim clock(Hz) <- I thing, you mean 84 MHz(in my aplication is freq. which go to TIM2)
    Prescaler <- what you mean "APB2 Prescaler" how is in STM32F4xx_Clock Configuration?

    RépondreSupprimer