#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++;
}
else{
position--;
}
}
}
跟楼主编的差不多,但是有一些不一样,你看这样行吗 |