我們使用的旋轉編碼器時序為
→ CW(順時針)
A ----------- -------------- HIGH
---------- LOW
← CCW(逆時針)
B -------- ------------------ HIGH
---------- LOW
ENA腳下降沿觸發(fā)時查詢B腳的電平,若為低電平時,由時序圖可知為順時針方向旋轉(CW),Position增加1
而ENA腳上升沿觸發(fā)時查詢B腳的電平,若為高電平時,由時序圖可知為順時針方向旋轉(CW),Position已增加1,故此時我們不再考慮
ENA腳下降沿觸發(fā)時查詢B腳的電平,若為高電平時,由時序圖可知為逆時針方向旋轉(CCW),Position減少1
而ENA腳上升沿觸發(fā)時查詢B腳的電平,若為低電平時,由時序圖可知為逆時針方向旋轉(CCW),Position已減少1,故此時我們不再考慮
編碼器模塊已設置了對ENA ENB的上拉以及按鍵SW的上拉
將ENA ENB SW依次連接到傳感器擴展板或者Arduino主控板的數字腳2、3、4上
VCC GND依次連接到+5V和GND上
下載運行代碼,打開串口監(jiān)視器Serial Monitor
旋轉編碼器可看到順時針旋轉時旋轉過一個編碼點后數值會增加1
逆時針旋轉則相應減少1
按下按鍵時旋轉編碼器模塊板載的LED會被點亮,同時串口監(jiān)視器中會顯示"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的電平以確認是順時針還是逆時針旋轉
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的電平以確認是順時針還是逆時針旋轉
if (digitalRead(ENCODER_B_PIN) == LOW)
position--;
}
}[/mw_shl_code]
承擔因您的行為而導致的法律責任,
本站有權保留或刪除有爭議評論。
參與本評論即表明您已經閱讀并接受
上述條款。