PaulS:
In the first code, you only trigger the interrupt handler when the A pin changes.
In the second code, you only trigger the interrupt handlers when the A and B pins fall.You need to trigger both handlers when the corresponding pin CHANGES.
int pulses; //Output pulses.
int encoderA = 3;
int encoderB = 2;
int pulsesChanged = 0;
void setup() {
Serial.begin(115200);
pinMode(encoderA, INPUT); //3
pinMode(encoderB, INPUT); //2
attachInterrupt(digitalPinToInterrupt(3), A_CHANGE, CHANGE);
attachInterrupt(digitalPinToInterrupt(2), B_CHANGE, CHANGE);
}//setup
void loop(){
if (pulsesChanged != 0) {
pulsesChanged = 0;
Serial.println(pulses);
}
}
void A_CHANGE(){
if( digitalRead(encoderB) == 0 ) {
if ( digitalRead(encoderA) == 0 ) {
// A fell, B is low
pulses--; // moving reverse
} else {
// A rose, B is low
pulses++; // moving forward
}
}else {
if ( digitalRead(encoderA) == 0 ) {
// B fell, A is high
pulses++; // moving reverse
} else {
// B rose, A is high
pulses--; // moving forward
}
}
pulsesChanged = 1;
}
void B_CHANGE(){
if ( digitalRead(encoderA) == 0 ) {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is low
pulses++; // moving forward
//Serial.println("a");
} else {
// B rose, A is low
pulses--; // moving reverse
//Serial.println("b");
}
} else {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is high
pulses--; // moving reverse
} else {
// B rose, A is high
pulses++; // moving forward
}
}
pulsesChanged = 1;
}
In this case the output is like this :
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0
-1
0