极性选择:控制输出波形是否反转。上升沿:不反转,下降沿:翻转
同时使用T1与T2进行计数,可有效防止毛刺信号带来的影响。
#include "stm32f10x.h" // Device header
/**
* 函 数:编码器初始化
* 参 数:无
* 返 回 值:无
*/
void Encoder_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);//开启定时器2的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructrue;
GPIO_InitStructrue.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStructrue.GPIO_Pin=GPIO_Pin_6 |GPIO_Pin_7;
GPIO_InitStructrue.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructrue);//初始化PA6/7引脚为上拉输入
TIM_TimeBaseInitTypeDef TimeBaseInitStructrue;
TimeBaseInitStructrue.TIM_ClockDivision= TIM_CKD_DIV1;//不分频
TimeBaseInitStructrue.TIM_CounterMode= TIM_CounterMode_Up;//向上计数模式
TimeBaseInitStructrue.TIM_Period= 65536-1;//ARR
TimeBaseInitStructrue.TIM_Prescaler= 1-1;//分频值//PSC
TimeBaseInitStructrue.TIM_RepetitionCounter= 0;//重复计数功能,此处不涉及
TIM_TimeBaseInit(TIM3,&TimeBaseInitStructrue);//读取结构体
/*输入捕获配置*/
TIM_ICInitTypeDef TIM_ICInitStructrue;
TIM_ICInit(TIM3,&TIM_ICInitStructrue);//预先初始化结构体
/*配置两相输入信号*/
TIM_ICInitStructrue.TIM_Channel=TIM_Channel_1;//选择通道1
TIM_ICInitStructrue.TIM_ICFilter=0xF;//滤波器
TIM_ICInit(TIM3,&TIM_ICInitStructrue);
TIM_ICInitStructrue.TIM_Channel=TIM_Channel_2;//选择通道2
TIM_ICInitStructrue.TIM_ICFilter=0xF;//滤波器
TIM_ICInit(TIM3,&TIM_ICInitStructrue);
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
//TIM_ICPolarity_Rising:输出不反向
TIM_Cmd(TIM3,ENABLE);
}
/**
* 函 数:获取输入波形计数值
* 参 数:无
* 返 回 值:计数器计数值
*/
int16_t Encoder_Get(void)
{
int16_t Temp;
Temp=TIM_GetCounter(TIM3);
TIM_SetCounter(TIM3,0);
return Temp;
}