一、编码器测速初始化
1、开启对应外设时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
2、配置编码器两个信号的GPIO
GPIO_InitTypeDef GPIO_InitStructure1;
GPIO_InitStructure1.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure1.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure1.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure1);
3、配置时基单元
注:这里不需要配置定时器时钟,编码器接口会托管时钟,编码器接口就是一个带方向的外部时钟
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
//指定时钟分频:不分频
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
//注:ARR和PSC取值需要在 0-65535之间
TIM_TimeBaseInitStructure.TIM_Period = 65536 - 1;
TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1;
//重复计数器的值
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
4、配置输入捕获
TIM_ICInitTypeDef TIM_ICInitStructure;
//通道1
//给结构体赋默认值,结构体里面的参数并没有使用完,防止出错
TIM_ICStructInit(&TIM_ICInitStructure);
//选择通道
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
//选择输入捕获的滤波器
TIM_ICInitStructure.TIM_ICFilter = 0xf;
//边沿检查的极性选择 这里的上升沿是高低电平极性不翻转
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
//通道2
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM_ICInitStructure.TIM_ICFilter = 0xf;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
5、配置编码器接口模式
//修改极性,只需要改一个就行,改两个依然不变
TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
6、启动定时器
TIM_Cmd(TIM3, ENABLE);
二、获取编码器位置
int16_t encoder_get(void)
{
return TIM_GetCounter(TIM3);
}
三、获取编码器速度
int16_t encoder_get(void)
{
int16_t temp;
temp = TIM_GetCounter(TIM3);
TIM_SetCounter(TIM3, 0);
return temp;
}