|
我们使用的旋转编码器时序为
→ CW(顺时针)
A ----------- -------------- HIGH
---------- LOW
← CCW(逆时针)
B -------- ------------------ HIGH
---------- LOW
RotaryEncoder
ENA脚下降沿触发时查询B脚的电平,若为低电平时,由时序图可知为顺时针方向旋转(CW),Position增加1
而ENA脚上升沿触发时查询B脚的电平,若为高电平时,由时序图可知为顺时针方向旋转(CW),Position已增加1,故此时我们不再考虑
ENA脚下降沿触发时查询B脚的电平,若为高电平时,由时序图可知为逆时针方向旋转(CCW),Position减少1
而ENA脚上升沿触发时查询B脚的电平,若为低电平时,由时序图可知为逆时针方向旋转(CCW),Position已减少1,故此时我们不再考虑
编码器模块已设置了对ENA ENB的上拉以及按键SW的上拉
将ENA ENB SW依次连接到传感器扩展板或者Arduino主控板的数字脚2、3、4上
VCC GND依次连接到+5V和GND上
下载运行代码,打开串口监视器Serial Monitor
旋转编码器可看到顺时针旋转时旋转过一个编码点后数值会增加1
逆时针旋转则相应减少1
按下按键时旋转编码器模块板载的LED会被点亮,同时串口监视器中会显示"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
http://www.openjumper.com
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脚下降沿中断触发
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脚上升沿中断触发
else{
// check channel B to see which way 查询ENB的电平以确认是顺时针还是逆时针旋转
if (digitalRead(ENCODER_B_PIN) == LOW)
position--;
}
}[/mw_shl_code]
|
|