0

I've met problem with timer configuration in STM32F051. I'am using StdPeriphLibrary, and I wish to generate an interrupt every 1 ms (freq = 1kHz).

This is the timer initialization:

void TIMER_initHardware(void)
{

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

    GPIO_InitTypeDef gpioInitStruct;
    gpioInitStruct.GPIO_Mode = GPIO_Mode_OUT;
    gpioInitStruct.GPIO_OType = GPIO_OType_PP;
    gpioInitStruct.GPIO_Pin = GPIO_Pin_12;
    gpioInitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
    gpioInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &gpioInitStruct);
    GPIO_ResetBits(GPIOA, GPIO_Pin_12);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef       TIM_OCInitStructure;
    NVIC_InitTypeDef        NVIC_InitStructure;

    NVIC_InitStructure.NVIC_IRQChannel                   = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority           = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    RCC_PCLKConfig(RCC_HCLK_Div1);

    SystemCoreClockUpdate();

    TIM_TimeBaseStructure.TIM_Period        = 0xFFFF; //32767;
    TIM_TimeBaseStructure.TIM_Prescaler     = (SystemCoreClock/1000000)-1;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode   = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    TIM_OCInitStructure.TIM_OCMode      = TIM_OCMode_Timing;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse       = TIMER_TIM2_ADD_1MS;
    TIM_OCInitStructure.TIM_OCPolarity  = TIM_OCPolarity_Low;

    TIM_OC1Init(TIM2, &TIM_OCInitStructure);
    TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

    TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE);

    TIM_Cmd(TIM2, ENABLE);

}

And here is the interrupt routine:

void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
        TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);
        tick = 1;
        if(GPIO_ReadOutputDataBit(GPIOA, GPIO_Pin_12))
        {
            GPIO_ResetBits(GPIOA, GPIO_Pin_12);
        }
        else
        {
            GPIO_SetBits(GPIOA, GPIO_Pin_12);
        }

}

This code Generates an interrupt every 66 ms - checked on oscilloscope.

There are no other interrupts used in application.

Draken
  • 3,134
  • 13
  • 34
  • 54

1 Answers1

0

Try to update your init code with:

...
TIM_TimeBaseStructure.TIM_Period        = 999;
...
TIM_OCInitStructure.TIM_Pulse       = 0;
...

You have set your timer clock to 1MHz (prescaler), so you need to subdivide this by 1000 (period = 1000-1 = 999). The pulse is not used here.

Also in your interrupt handler, I am not sure that you need to do this and I think it can be removed:

TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);
Guillaume Michel
  • 1,189
  • 8
  • 14