我們使用的旋轉(zhuǎn)編碼器時(shí)序?yàn)?/span>
→ CW(順時(shí)針)
A ----------- -------------- HIGH
---------- LOW
← CCW(逆時(shí)針)
B -------- ------------------ HIGH
---------- LOW
ENA腳下降沿觸發(fā)時(shí)查詢B腳的電平,若為低電平時(shí),由時(shí)序圖可知為順時(shí)針方向旋轉(zhuǎn)(CW),Position增加1
而ENA腳上升沿觸發(fā)時(shí)查詢B腳的電平,若為高電平時(shí),由時(shí)序圖可知為順時(shí)針方向旋轉(zhuǎn)(CW),Position已增加1,故此時(shí)我們不再考慮
ENA腳下降沿觸發(fā)時(shí)查詢B腳的電平,若為高電平時(shí),由時(shí)序圖可知為逆時(shí)針方向旋轉(zhuǎn)(CCW),Position減少1
而ENA腳上升沿觸發(fā)時(shí)查詢B腳的電平,若為低電平時(shí),由時(shí)序圖可知為逆時(shí)針方向旋轉(zhuǎn)(CCW),Position已減少1,故此時(shí)我們不再考慮
編碼器模塊已設(shè)置了對(duì)ENA ENB的上拉以及按鍵SW的上拉
將ENA ENB SW依次連接到傳感器擴(kuò)展板或者Arduino主控板的數(shù)字腳2、3、4上
VCC GND依次連接到+5V和GND上
下載運(yùn)行代碼,打開串口監(jiān)視器Serial Monitor
旋轉(zhuǎn)編碼器可看到順時(shí)針旋轉(zhuǎn)時(shí)旋轉(zhuǎn)過一個(gè)編碼點(diǎn)后數(shù)值會(huì)增加1
逆時(shí)針旋轉(zhuǎn)則相應(yīng)減少1
按下按鍵時(shí)旋轉(zhuǎn)編碼器模塊板載的LED會(huì)被點(diǎn)亮,同時(shí)串口監(jiān)視器中會(huì)顯示"Switch Pressed"
[mw_shl_code=cpp,true]/*
RotaryEncoder
Read a rotary encoder with interrupts
Read the press action with digitalread
Encoder&Switch hooked up with common to +5V
ENCODER_A_PIN to pin 2
ENCODER_A_PIN to pin 3
SWITCH_PIN to pin 4
Published by ArduinoCN&OpenJumper.For surport
materials and a full range of system boards &
periphrals please visit :
http://www.arduino.cn
created & modified 15 Dec 2012
by i3water
*/
#define ENCODER_A_PIN 2
#define ENCODER_B_PIN 3
#define SWITCH_PIN 4
long position;
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");
}
}
Serial.print("Position: ");
Serial.println(position, DEC);
delay(1000);
}
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--;
}
}[/mw_shl_code]
承擔(dān)因您的行為而導(dǎo)致的法律責(zé)任,
本站有權(quán)保留或刪除有爭(zhēng)議評(píng)論。
參與本評(píng)論即表明您已經(jīng)閱讀并接受
上述條款。