使用STM32的PWM輸入功能計(jì)算輸入PWM的周期
1、時(shí)鐘部分,TIMER2的時(shí)鐘頻率,我是初始化為36M.
本文引用地址:http://www.ex-cimer.com/article/148408.htmRCC_PCLK1Config(RCC_HCLK_Div2); //設(shè)置低速AHB時(shí)鐘=系統(tǒng)時(shí)鐘/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計(jì)數(shù)器
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE); //使能CC2中斷請(qǐng)求
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時(shí)鐘經(jīng)過(guò)分頻率后,時(shí)鐘的精度誤差會(huì)隨分頻值變大而變大。在不分頻的情況下,我檢測(cè)1KHz的PWM輸入信號(hào),誤差為0.5us。在18分頻的情況下,誤差已經(jīng)不能看了。測(cè)量100Hz,根據(jù)捕獲值計(jì)算出來(lái)卻是105Hz。
確實(shí)如STM32朋友所講,在分頻處我理解錯(cuò)了,分頻值=TIM_TimeBaseStructure.TIM_Prescaler +1,所以如果要分18分頻,只要將TIM_Prescaler=17即可。經(jīng)這樣修改后測(cè)量誤差在萬(wàn)分之5以?xún)?nèi)。謝謝STM32朋友的提醒!!(上面的誤解我就不刪除了,留做以后警記,呵呵!)
pwm相關(guān)文章:pwm原理
塵埃粒子計(jì)數(shù)器相關(guān)文章:塵埃粒子計(jì)數(shù)器原理
評(píng)論