Arduino、AB相增量式光电编码器测位移和速度方向
程序员文章站
2022-07-07 11:19:07
...
利用Arduino、增量式光电编码器测量速度、方向、位移。
学校的一个项目作业,实测有效,若有改进的地方还需大佬们指点。
-
材料:
Arduino mega 2560
2个2k电阻(红白之间2k,红绿之间2k)
分辨率400 AB相增量式编码器
pc
-
编码器简介
-
连线图
int0 为接口2,int1为接口3。
-
测速原理
脉冲数/(编码器分辨率*时间)
A脉冲为下降沿,B脉冲为高电平,方向为正;
A脉冲为下降沿,B脉冲为低电平,方向为负。
-
程序:
#include <MsTimer2.h> //中断库
int pinA=2; // 定义2号端口为A脉冲输入端口
int pinB=3;// 定义3号端口为B脉冲输入端口
int ppsA=0; //记录A脉冲的次数
int m=0; //定义位移
char a='+';
char b='-';
char c; //方向
float velocity=0; //速度
float v(float n) //转速计算函数
{
float vel =n/40; // n/(400*0.1)
return vel;
}
void flash()
{
int w=ppsA;
velocity=v(w); //计算转速
if (velocity!=0)
{
Serial.print(c);
}
if(c==a)
{
m=m+ppsA*360/400; //计算正位移
}
else if(c==b)
{
m=m-ppsA*360/400; //计算负位移
}
Serial.print(velocity); // 将获取的数字信号值打印到串口显示
Serial.print("r/s ");
Serial.print(m);
Serial.println("°");
ppsA=0; //脉冲A计数归0
}
void setup()
{
Serial.begin(9600);
attachInterrupt(0,CountA, FALLING);//检测脉冲下降沿中断,并转到CountA函数
MsTimer2::set(100, flash); // 中断设置函数,0.1s
MsTimer2::start(); //开始计时
}
void loop()
{
}
void CountA()
{
if(digitalRead(pinB) == HIGH) //B脉冲为高电平
{
c=a;
}
if(digitalRead(pinB) == LOW) //B脉冲为高电平
{
c=b;
}
ppsA++;
}