void TIM_Config_Encoder(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/*-------------------第1步--------------------*/
//使能定时器时钟和相关GPIO时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_AHB1PeriphClockCmd (RCC_AHB1Periph_GPIOC, ENABLE);
/*-------------------第2步--------------------*/
//初始化定时器编码器接口输入通道引脚
/* 定时器复用引脚 */
GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_TIM3);
GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_TIM3);
/* 配置定时器输入脚 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/*-------------------第3步--------------------*/
//定义编码器旋转一圈的计数值溢出值,用于计算圈数
TIM_TimeBaseStructure.TIM_Period = 4000-1;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; // 计数方式
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);// 初始化定时器
/*-------------------第4步--------------------*/
// 编码器模式设置
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Falling, TIM_ICPolarity_Falling);//编码器模式3
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;//
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 6;//滤波器值,去输入信号抖动
TIM_ICInit(TIM3, &TIM_ICInitStructure);
/*-------------------第5步--------------------*/
//定时器中断配置
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; // 设置中断来源
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; // 设置抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 4;// 设置子优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ClearFlag(TIM3, TIM_FLAG_Update); //清楚所有标志位
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //允许TIM3溢出中断
TIM_ITConfig(TIM3,TIM_IT_CC1,ENABLE); //允许TIM3通道1比较中断
/*-------------------第6步--------------------*/
TIM_SetCounter(TIM3, 0);
TIM_Cmd(TIM3, ENABLE);//使能定时器
}