标题: arduino处理增量式光电编码器并串口显示转动角度 [打印本页]

作者: ai1161647920    时间: 2018-4-19 17:46
标题: arduino处理增量式光电编码器并串口显示转动角度
一、线路连接
Vcc连接正极
0v连接负极
AB各连接一个引脚(下面设置)
二、程序与结果
1. 程序
#define ENCODER_A_PIN 2
#define ENCODER_B_PIN 3
#define SWITCH_PIN    4
long position;
double corg = LOW;
void setup(){
  //setup our pins 初始化我们的需要的引脚
  pinMode(ENCODER_A_PIN, INPUT);
  pinMode(ENCODER_B_PIN, INPUT);
  pinMode(SWITCH_PIN, INPUT);
  attachInterrupt(0, read_quadrature, CHANGE);
  //setup our serial 初始化Arduino串口
  Serial.begin(9600);
}
void loop(){
   if (digitalRead(SWITCH_PIN) == LOW){
     delay(10);
     if (digitalRead(SWITCH_PIN) == LOW){
      // Serial.println("Switch Pressed");
     }
   }
   corg = position*360/1024;
   Serial.println(corg, DEC);
   delay(100);
}
void read_quadrature(){  
  // found a low-to-high on channel A ENA脚下降沿中断触发
  if (digitalRead(ENCODER_A_PIN) == LOW){   
    // check channel B to see which way 查询ENB的电平以确认是顺时针还是逆时针旋转
    if (digitalRead(ENCODER_B_PIN) == LOW)
      position++;
  }
  // found a high-to-low on channel A ENA脚上升沿中断触发
  else{
    // check channel B to see which way 查询ENB的电平以确认是顺时针还是逆时针旋转
    if (digitalRead(ENCODER_B_PIN) == LOW)
      position--;
  }
}
2. 结果
发布arduino程序,打开串口监视器,转动编码器可以得到相应的角度。
3. Matlab读取角度值并做图
s=serial('COM2');
set(s,'BaudRate',9600);
fopen(s);
interval=5000;
passo=1;
t=1;
x=0;
while(t<interval)
b=str2num(fgetl(s));
x=[x,b];
plot(x);
grid
t=t+passo;
drawnow;
end
fclose(s);






欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1