標(biāo)題: arduino處理增量式光電編碼器并串口顯示轉(zhuǎn)動(dòng)角度 [打印本頁(yè)]

作者: ai1161647920    時(shí)間: 2018-4-19 17:46
標(biāo)題: arduino處理增量式光電編碼器并串口顯示轉(zhuǎn)動(dòng)角度
一、線路連接
Vcc連接正極
0v連接負(fù)極
AB各連接一個(gè)引腳(下面設(shè)置)
二、程序與結(jié)果
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腳下降沿中斷觸發(fā)
  if (digitalRead(ENCODER_A_PIN) == LOW){   
    // check channel B to see which way 查詢ENB的電平以確認(rèn)是順時(shí)針還是逆時(shí)針旋轉(zhuǎn)
    if (digitalRead(ENCODER_B_PIN) == LOW)
      position++;
  }
  // found a high-to-low on channel A ENA腳上升沿中斷觸發(fā)
  else{
    // check channel B to see which way 查詢ENB的電平以確認(rèn)是順時(shí)針還是逆時(shí)針旋轉(zhuǎn)
    if (digitalRead(ENCODER_B_PIN) == LOW)
      position--;
  }
}
2. 結(jié)果
發(fā)布arduino程序,打開串口監(jiān)視器,轉(zhuǎn)動(dòng)編碼器可以得到相應(yīng)的角度。
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.torrancerestoration.com/bbs/) Powered by Discuz! X3.1