在本教程中,您將學習如何將增量旋轉(zhuǎn)編碼器與Arduino連接,以讀取旋鈕的運動。這對于在機器人和其他應用程序中創(chuàng)建用戶界面或讀取機械位置非常有用。
您需要的器件
Arduino開發(fā)板
1x 增量式旋轉(zhuǎn)編碼器(像這樣)
4個10 kΩ電阻(R1、R2)
2x 0.1uF 電容器 (C1, C2)
面包板
原理圖和試驗板設(shè)置
請注意,在此原理圖中,我直接使用旋轉(zhuǎn)編碼器,因此它需要一些額外的元件。但您也可以購買旋轉(zhuǎn)編碼器板,在板上包含這些額外的組件,以使連接更簡單。
原理圖中的VDD僅指Arduino的5V電壓。
連接此旋轉(zhuǎn)編碼器所需的額外組件的連接取自旋轉(zhuǎn)編碼器數(shù)據(jù)表中的建議濾波電路。如果您使用的是不同的編碼器,請務必查看數(shù)據(jù)表中的“建議濾波電路”,因為它可能不同。
它是如何工作的
該電路的工作原理是查看旋轉(zhuǎn)編碼器的兩個引腳 A 和 B,并檢查它們中哪一個先于另一個引腳為高電平。如果 A 先于 B 走高,那就是一個方向。如果 B
先于 A 走高,則方向相反。
連接Arduino旋轉(zhuǎn)編碼器電路
在下圖中,您可以看到如何將完整的示例電路連接到面包板上,以及將其連接到Arduino所需的接線。
分步說明
將旋轉(zhuǎn)編碼器連接到面包板。
將兩個10 kΩ電阻R1和R2從A和B置于5V。
將兩個 10 kΩ 電阻 R3 和 R4 分別從 A 和 B 連接到 Arduino 數(shù)字引腳 10 和 11。
如圖所示放置0.1uF電容(C1和C2),使編碼器信號去抖動。
將 C 點接地。
使用 USB 數(shù)據(jù)線將 Arduino 連接到您的計算機。
將以下代碼上傳到您的 Arduino。此代碼初始化旋轉(zhuǎn)編碼器,并在每次轉(zhuǎn)動編碼器時使用中斷來更新位置計數(shù)。
結(jié)果將打印到串行端口,以便您可以從串行監(jiān)視器中讀取結(jié)果。
// Define the pins used for the encoder
const int encoderPinA = 10;
const int encoderPinB = 11;
// Variables to keep the current and last state
volatile int encoderPosCount = 0;
int lastEncoded = 0;
void setup() {
Serial.begin(9600);
// Set encoder pins as input with pull-up resistors
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
// Attach interrupts to the encoder pins
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
}
void loop() {
static int lastReportedPos = -1; // Store the last reported position
if (encoderPosCount != lastReportedPos) {
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
lastReportedPos = encoderPosCount;
}
}
void updateEncoder() {
int MSB = digitalRead(encoderPinA); // MSB = most significant bit
int LSB = digitalRead(encoderPinB); // LSB = least significant bit
int encoded = (MSB < < 1) | LSB; // Converting the 2 pin value to single number
int sum = (lastEncoded < < 2) | encoded; // Adding it to the previous encoded value
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderPosCount++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderPosCount--;
lastEncoded = encoded; // Store this value for next time
}
上傳此代碼后,您可以以 9600 的波特率打開串行監(jiān)視器,以查看編碼器的移動在旋轉(zhuǎn)時的變化。
如果編碼器值不穩(wěn)定或未按預期變化,請根據(jù)原理圖仔細檢查接線,并確保電阻器和電容器正確放置以進行去抖動。
審核編輯:陳陳
-
旋轉(zhuǎn)編碼器
+關(guān)注
關(guān)注
5文章
159瀏覽量
26024 -
Arduino
+關(guān)注
關(guān)注
188文章
6477瀏覽量
187819
發(fā)布評論請先 登錄
相關(guān)推薦
評論