STM32F051定时器配置

时间:2017-06-06 13:47:23

标签: timer stm32f0

我在STM32F051中遇到了定时器配置问题。 我正在使用StdPeriphLibrary,我希望每1 ms生成一次中断(freq = 1kHz)。

这是计时器初始化:

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);

}

这是中断程序:

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);
        }

}

此代码每66 ms生成一次中断 - 在示波器上检查。

应用程序中没有使用其他中断。

1 个答案:

答案 0 :(得分:0)

尝试使用以下命令更新您的初始化代码:

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

您已将定时器时钟设置为1MHz(预分频器),因此您需要将其细分为1000(周期= 1000-1 = 999)。这里不使用脉冲。

同样在你的中断处理程序中,我不确定你是否需要这样做,我认为它可以删除:

TIM_SetCompare1(TIM2, TIM_GetCapture1(TIM2) + TIMER_TIM2_ADD_1MS);