在本篇文章中,我們將學習如何在Arduino開發(fā)板上使用旋轉編碼器。我們將以帶符號的數(shù)字同時顯示順時針和逆時針方向的編碼值。
所需的組件
● Arduino UNO開發(fā)板
● 旋轉編碼器
● 1602 LCD顯示屏
● 連接電線
● 面包板
旋轉編碼器
旋轉編碼器(Rotary Encoder),也稱為軸編碼器,是一種機電設備,可將軸或軸的角位置或運動轉換為模擬或數(shù)字輸出信號。旋轉編碼器有兩種主要類型:絕對式和增量式。絕對值編碼器的輸出指示當前軸位置,從而使其成為角度傳感器。增量編碼器的輸出提供有關軸運動的信息,通常將其所在位置處理為位置、速度和距離等信息。
連接電路圖
下面的電路圖簡單演示了如何在Arduino上使用旋轉編碼器。在面包板或PCB上組裝電路。
旋轉編碼器如何工作?
編碼器具有一個磁盤,該磁盤具有均勻分布的接觸區(qū),這些接觸區(qū)連接到公共引腳C和兩個其他單獨的接觸引腳A和B,如下所示。
當磁盤逐步開始旋轉時,引腳A和B將開始與公共引腳接觸,因此將產(chǎn)生兩個方波輸出信號。
如果僅對信號的脈沖進行計數(shù),則可以使用兩個輸出中的任何一個來確定旋轉位置。但是,如果我們也要確定旋轉方向,則需要同時考慮兩個信號。
我們可以注意到,兩個輸出信號彼此之間相差90度。如果編碼器順時針旋轉,則輸出A將在輸出B之前。
因此,如果我們每次計算信號從高到低或從低到高變化的步數(shù),我們就會注意到兩個輸出信號的值相反。反之亦然,如果編碼器逆時針旋轉,則輸出信號具有相等的值。因此,考慮到這一點,我們可以輕松地對控制器進行編程以讀取編碼器的位置和旋轉方向。
源代碼/程序
#include 《LiquidCrystal.h》
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define outputA 6
#define outputB 7
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (9600);
lcd.begin(16,2);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}
void loop() {
aState = digitalRead(outputA); // Reads the “current” state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
lcd.clear();
} else {
counter --;
lcd.clear();
}
Serial.print(“Position: ”);
Serial.println(counter);
lcd.print(“Position: ”);
lcd.setCursor(10, 0);
lcd.print(counter);
}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
編輯:hfy
-
編碼器
+關注
關注
45文章
3667瀏覽量
135237 -
開發(fā)板
+關注
關注
25文章
5121瀏覽量
98192 -
Arduino
+關注
關注
188文章
6477瀏覽量
187816
發(fā)布評論請先 登錄
相關推薦
評論