5 Pin Rotary Encoder

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;
  }
}
  1. NEVER do serial I/O in an interrupt service routine. Instead, declare EncoderPos 'volatile', then in loop() read it and print it to serial.

  2. In the ISR, it's better to read both encoder pins simultaneously. Pins 2 and 3 are both on port D and are bits 2 and 3 respectively, so you can do this by reading PORTD and then use bit masking to look at those 2 pins, like this:

uint8_t state = (PORTD >> 2) & 3;
  1. I believe you have the state tables wrong. These encoders output a 2-bit Gray code, so every transition involves only 1 bit changing. Therefore you will never get 0->3, 3->0, 1->2 or 2->1.