Hi everyone
I am having trouble with a quadrature decoder program, it seems to work- but when the encoder is spinning fast, i'm starting to get wrong values (for example, a full revolution yields a count of 1500~ instead of 2048)
Here's the code:
int pulses;
int deg = 0;
int encoderA = 2;
int encoderB = 3;
int pulsesChanged = 0;
void setup(){
Serial.begin(115200);
Serial.println("start");
pinMode(encoderA, INPUT);
pinMode(encoderB, INPUT);
attachInterrupt(0, A_CHANGE, CHANGE);
attachInterrupt(1, 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++;
}
} else {
if ( digitalRead(encoderA) == 0 ) {
// A fell, B is high
pulses++; // "positive" spin direction
} else {
// A rose, B is high
pulses--; // "negaitve" direction
}
}
// tell the loop that the pulses have changed
pulsesChanged = 1;
}
void B_CHANGE(){
if ( digitalRead(encoderA) == 0 ) {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is low
pulses++; // pos
} else {
// B rose, A is low
pulses--; // neg
}
} else {
if ( digitalRead(encoderB) == 0 ) {
// B fell, A is high
pulses--; // pos
} else {
// B rose, A is high
pulses++; // neg
}
}
// tell the loop that the pulses have changed
pulsesChanged = 1;
}
My encoder is 2048P/R (though it says 1024 on it, but reality is reality...)
I cracked my head on this and can't find problems with this fairly simple code, it should be working.
I'd appreciate any help with finding issues in the code, or if anyone has advice on how to make changes to accommodate the high rates needed- suggestions are always welcome
Thank you