使用STM32的PWM輸入功能計算輸入PWM的周期
1、時鐘部分,TIMER2的時鐘頻率,我是初始化為36M.
RCC_PCLK1Config(RCC_HCLK_Div2); //設(shè)置低速AHB時鐘=系統(tǒng)時鐘/2
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9); // 倍頻系數(shù)為9 PLLCLK="8"*9=72
2、TIMER初始化
TIM_DeInit(TIM2);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 18;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV4;
TIM_ICInitStructure.TIM_ICFilter = 0x0;
TIM_PWMIConfig(TIM2, &TIM_ICInitStructure);
TIM_SelectInputTrigger(TIM2, TIM_TS_TI1FP1);
TIM_SelectSlaveMode(TIM2, TIM_SlaveMode_Reset); //復(fù)位模式為從模式
TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable); //使能主從模式
TIM_Cmd(TIM2, ENABLE); //使能TIM2計數(shù)器
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE); //使能CC2中斷請求
3、TIMER中斷處理
void TIM2_IRQHandler(void)
{
/* Clear TIM2 Capture compare interrupt pending bit */
TIM_ClearITPendingBit(TIM2, TIM_IT_CC2);
/* Get the Input Capture value */
IC2_Value = TIM_GetCapture2(TIM2);
}
注意事項(xiàng):
不知道為什么,STM32的TIMER時鐘經(jīng)過分頻率后,時鐘的精度誤差會隨分頻值變大而變大。在不分頻的情況下,我檢測1KHz的PWM輸入信號,誤差為0.5us。在18分頻的情況下,誤差已經(jīng)不能看了。測量100Hz,根據(jù)捕獲值計算出來卻是105Hz。
確實(shí)如STM32朋友所講,在分頻處我理解錯了,分頻值=TIM_TimeBaseStructure.TIM_Prescaler +1,所以如果要分18分頻,只要將TIM_Prescaler=17即可。經(jīng)這樣修改后測量誤差在萬分之5以內(nèi)。謝謝STM32朋友的提醒!!(上面的誤解我就不刪除了,留做以后警記,呵呵!)