/* LEE 抄袭并小改的版本,原版版权:三水
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(){
Serial.print("Position: ");
Serial.println(position, DEC);
// delay(1000);
}
void read_quadrature(){
// found a low-to-high on channel A ENA脚下降沿中断触发
if (bitRead(PIND,2) == LOW){
// check channel B to see which way 查询ENB的电平以确认是顺时针还是逆时针旋转
if (bitRead(PIND,3) == LOW)
position++;
}
// found a high-to-low on channel A ENA脚上升沿中断触发
else{
// check channel B to see which way 查询ENB的电平以确认是顺时针还是逆时针旋转
if (bitRead(PIND,3) == LOW)
position--;
}
} |