1、时钟部分,TIMER2的时钟频率,我是初始化为36M.
RCC_PCLK1Config(RCC_HCLK_Div2); //设置低速AHB时钟=系统时钟/2
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9); // 倍频系数为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); //复位模式为从模式
TIM_SelectMasterSlaveMode(TIM2, TIM_MasterSlaveMode_Enable); //使能主从模式
TIM_Cmd(TIM2, ENABLE); //使能TIM2计数器
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);
}
注意事项:
不知道为什么,STM32的TIMER时钟经过分频率后,时钟的精度误差会随分频值变大而变大。在不分频的情况下,我检测1KHz的PWM输入信号,误差为0.5us。在18分频的情况下,误差已经不能看了。测量100Hz,根据捕获值计算出来却是105Hz。
确实如STM32朋友所讲,在分频处我理解错了,分频值=TIM_TimeBaseStructure.TIM_Prescaler +1,所以如果要分18分频,只要将TIM_Prescaler=17即可。经这样修改后测量误差在万分之5以内。
上一篇:STM32驱动1602程序
下一篇:基于keil C mdk开发环境的stm32的USB接口单片机程序设计
推荐阅读最新更新时间:2024-03-16 15:56