2017-06-06 61 views
0

我遇到了STM32F051中定時器配置問題。 我使用StdPeriphLibrary,我希望每1毫秒產生一次中斷(頻率= 1kHz)。STM32F051定時器配置

這是定時器初始化:

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

} 

此代碼生成每66ms中斷 - 在示波器檢查。

在應用程序中沒有使用其他中斷。

回答

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