void encoder_left_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);//开启TIM3时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE);//开启GPIOB时钟
GPIO_PinAFConfig(GPIOD,GPIO_PinSource12,GPIO_AF_TIM4);//PB0引脚复用
GPIO_PinAFConfig(GPIOD,GPIO_PinSource13,GPIO_AF_TIM4);//PB1引脚服用
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13; //GPIOB0,GPIOB1
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
GPIO_Init(GPIOD,&GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 65535; //设置下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler = 0; //设置用来作为TIMx时钟频率除数的预分频值 不分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
//设置定时器为编码器模式 IT1 IT2为上升沿和下降沿都计数四倍频
TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12,TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_ICFilter = 0; //输入滤波器
TIM_ICInit(TIM4, &TIM_ICInitStructure);
TIM_ClearFlag(TIM4, TIM_FLAG_Update); //清楚所有标志位
TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE); //允许中断更新
TIM4->CNT = 0;
TIM_Cmd(TIM4, ENABLE); //使能TIM3
}
配置定时器的编码器接口的函数。 看reference manual可以看到有那么定时器有编码器接口功能。一般是定时器的通道1和2才能作为编码器输入口,对应编码器输出的两相。
TIMx参数就是使用哪个定时器作为编码器接口的捕捉定时器。
TIM_EncoderMode参数是模式,是单相计数(只能反映速度)还是两相计数(速度和方向)。
TIM_IC1Polarity和TIM_IC2Polarity参数就是通道1、2的捕捉极性。
比如:
1. Countingon TI1 only:TI2为高时(第一行):TI1上升沿则向下计数,下降沿则向上计数。
1时刻:TI2为低电平,TI1上升沿跳变,计数器向上计数;
3时刻:TI2为高电平,TI1下降沿跳变,计数器仍然向上计数。
2. Countingon TI1 and TI2:一个周期完成4次跳变。精度提高
1时刻:TI2为低电平,TI1上升沿跳变,计数器向上计数;
2时刻:TI1为高电平,TI2上升沿跳变,计数器仍然向上计数;
3时刻:TI2为高电平,TI1下降沿跳变,计数器仍然向上计数;
4时刻:TI1为低电平,TI2下降沿跳变,计数器仍然向上计数。
相关文章









