0

我在 STM32F051 中遇到了定时器配置问题。我正在使用 StdPeriphLibrary,我希望每 1 毫秒(频率 = 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 生成一个中断 - 在示波器上检查。

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

4

1 回答 1

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);
于 2017-06-07T13:34:34.120 回答