I am working on a project where I'm connecting a 200 P/R mechanical rotary encoder (Yumo E6A2-CW3C) to a gear on a reel controlled by an electric motor. The purpose of the encoder in this project is to measure the number of rotations the reel makes. I'm using interrupts and pasted below is the code that I've compiled through exhaustively going through the Rotary Encoder Playground and other resources online. I'm not sure but I think the problem is in debouncing. When this code is uploaded to the Arduino, it gives an output in the serial monitor until the encoder is spinning too quickly. I am extremely inexperienced with Arduino and any help would be incredibly appreciated.
Thanks!
int state, prevstate = 0, count = 0;
int nextEncoderState[4] = { 2, 0, 3, 1 };
int prevEncoderState[4] = { 1, 3, 0, 2 };
int EncoderPinA = 2;
int EncoderPinB = 3;
int EncoderPos = 0;
void setup()
{
pinMode(EncoderPinA, INPUT);
pinMode(EncoderPinB, INPUT);
pinMode(6, OUTPUT);
digitalWrite(6, LOW);
digitalWrite(EncoderPinA, HIGH);
digitalWrite(EncoderPinB, HIGH);
attachInterrupt(0, doEncoder, CHANGE);
attachInterrupt(1, doEncoder, CHANGE);
Serial.begin(115200);
}
void loop()
{
// delay(1000);
}
void doEncoder(){
state = (digitalRead(EncoderPinA) << 1) | digitalRead(EncoderPinB);
if (state != prevstate) {
if (state == nextEncoderState[prevstate]) {
EncoderPos = EncoderPos + 1;
} else if (state == prevEncoderState[prevstate]) {
EncoderPos = EncoderPos - 1;
}
Serial.println(EncoderPos, DEC);
prevstate = state;
}
}