Arduino旋轉編碼器測試


做為旋轉編碼器學習過程的記錄,原理就不詳細介紹了,網上有很多。

先上一張時序圖

正常旋轉時顯示
順時針時序
CLK:1 DT:1
CLK:1 DT:0
CLK:0 DT:0
CLK:0 DT:1
CLK:1 DT:1
逆時針時序
CLK:1 DT:1
CLK:0 DT:1
CLK:0 DT:0
CLK:1 DT:0
CLK:1 DT:1

用網上找的程序測試發現會出現錯誤編碼,於是自己修理一下檢測方法,對整個時序進行檢查,錯誤解決。

程序通過串口輸出旋轉方向和按鍵。

 1 int CLKbtn = 12;
 2 int DTbtn = A2;
 3 int SWbtn = A1;
 4 int oldA = LOW;
 5 int oldB = LOW;
 6 bool lastButtonStatus = false;
 7 unsigned char check = 0x00;
 8 void setup()
 9 {
10   Serial.begin(9600);
11   pinMode(CLKbtn, INPUT);
12   pinMode(DTbtn, INPUT);
13   pinMode(SWbtn, INPUT);
14   digitalWrite(SWbtn, HIGH);//連接按鈕的引腳設為上拉
15 }
16 void loop()
17 {
18   int newA = digitalRead(CLKbtn);
19   int newB = digitalRead(DTbtn);
20   int SW = digitalRead(SWbtn);
21  
22   //按鍵檢測
23   bool buttonStatus = !digitalRead(SWbtn);//高電平時未按下,狀態為false
24   if (buttonStatus != lastButtonStatus)
25   { 
26      buttonStatus = !digitalRead(SWbtn);
27     delay(20);//去抖動
28     if (buttonStatus != lastButtonStatus)
29     {
30       Serial.println(buttonStatus ? "pressed" : "released");
31       lastButtonStatus = buttonStatus;//保存當前狀態
32     }
33   }
34   //旋轉檢測
35   if (newA != oldA || newB != oldB)//變化時
36   {
37     check = (check << 2) + (newA << 1) + newB; //將變化的時序按位放入,用於對比。
38     if (newA == HIGH && newB == HIGH)//旋轉結束
39     {
40       if (check == 0x87) //順時針 10 00 01 11
41         Serial.println("順時針");
42       else if (check == 0x4B) //逆時針 01 00 10 11
43         Serial.println("逆時針");
44       else
45       {
46         Serial.println("error");
47       }
48     }
49     oldA = newA;
50     oldB = newB;
51   }
52 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM