一、線路連接 Vcc連接正極 0v連接負極 A、B各連接一個引腳(下面設置) 二、程序與結果 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);
|