STM32cubemx下读取智能车mini编码器
STM32cubemx下读取智能车mini编码器
大一刚学完32,就淘了台智能车C车,并且还从某鱼上买了两个mini编码器,看着靓车,幻想着自己的小车车能够在赛场上奔驰,结果还没开始调pid,就卡在读取编码器上,搞了好几天人都麻了,之前调过霍尔编码器,用32的编码器模式一下就读到了,这里虽然能够读到但是经过测试,每转一圈,读到的编码值竟然不一样,试了很多方法,输入捕获,编码器模式,外部中断,最终采用了外部中断加上input的IO的形式来读取编码器数值。
-首先,附上用stmstudio调的速度环 -第二是STMcubemx外部中断和input的IO口所需的配置 -第三通过外部中断来读取编码器的值这里采用累加的方式
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)//通过外部中断捕获编码器值
{
if(GPIO_Pin ==EN1_Pin)
{
buhuo[0]++;//1024线
}
else if(GPIO_Pin ==EN2_Pin)
{
buhuo[2]++;//512线
}
}
-第四对读出来的数据进行数据处理
#define Read1 HAL_GPIO_ReadPin(KEY1_GPIO_Port,KEY1_Pin)
#define Read2 HAL_GPIO_ReadPin(KEY2_GPIO_Port,KEY2_Pin)
delta=buhuo[0]-buhuo[1];//计算误差
delta1=buhuo[2]-buhuo[3];
buhuo[3]=buhuo[2];
buhuo[1]=buhuo[0];
if(Read1==1)//右编码器值
{
encoder[0]=encoder[0]+delta;//最终编码器值
}
else if(Read1==0)
{
encoder[0]=encoder[0]-delta;
}
if(Read2==1)//左编码器值
{
encoder[2]=encoder[2]+delta1;//最终编码器值
}
else if(Read2==0)
{
encoder[2]=encoder[2]-delta1;
}
motor_left_position=encoder[0]*2;
motor_right_position=-encoder[2];
motor_right_speed = -(encoder[2]-encoder[3])*1;
motor_left_speed = (encoder[0]-encoder[1]);
motor_middle_position=(motor_left_position+motor_right_position)/2;
motor_middle_speed=(motor_left_speed+motor_right_position)/2;
encoder[3]=encoder[2];
encoder[1]=encoder[0];
这样最终能够读出来较为精准的速度和位置 最后附上接线图,另一边接线类似 哈哈,萌新第一次发篇,请多指教。
