Encoder Count Overflow

Hi,

Currently I’m using Pololu 12V, 100:1 Gear Motor w/Encoder and Arduino Mega board for my project and I need to get the position value using the encoder. The problem comes when the encoder count reach appx. 3200/-3200 (5 revolutions), the value changes sign. So, how could I fix the overflow problem so that it can count more than 3200/-3200. I would really appreciate for any help.

This is the code I have written:

int encoderPos_2 = 0; 
int b_enable = 5;
int b_input1 = 3;
int b_input2 = 2;
int encoder_C = 21;  
int encoder_D = 20;  

void setup()
{
  pinMode(b_enable,OUTPUT);  
  pinMode(b_input1,OUTPUT);
  pinMode(b_input2,OUTPUT);
  pinMode(encoder_C,INPUT);
  pinMode(encoder_D,INPUT);
    
  attachInterrupt(2,doEncoderC,CHANGE);
  attachInterrupt(3,doEncoderD,CHANGE);
  
  Serial.begin(115200);
}

void loop()
{
  analogWrite(b_enable,45);
  digitalWrite(b_input1,HIGH);
  digitalWrite(b_input2,LOW);
  Serial.println(encoderPos_2);  
}

void doEncoderC()
{
 if(digitalRead(encoder_C) == HIGH) //Check low to high channel A
 {
  if(digitalRead(encoder_D) == LOW) //check channel B for direction
    encoderPos_2++;  //CW
  else
   encoderPos_2--;  //CCW 
 }
 else      //Must be high to low on channel A
 {
  if(digitalRead(encoder_D) == HIGH)  //check channel B for direction
   encoderPos_2++;   //CW
  else
    encoderPos_2--;   //CCW
 }
}

void doEncoderD()
{
  if(digitalRead(encoder_D) == HIGH)    //check low to high on channel B 
  {
    if(digitalRead(encoder_C) == HIGH)  //check channel A for direction
      encoderPos_2++;
    else
      encoderPos_2--;
  }
  
  else
  {
     if(digitalRead(encoder_C) == LOW)
      encoderPos_2++;
     else
      encoderPos_2--; 
  }
}

Hello.

I am sorry you are having problems using your motor with encoder. It looks like you might have a typo in your last post. In general, integers are stored as 16-bit values on the Arduino, so the range should be -32768 to 32767. I do not expect overflow to occur at -3200 and 3200. Did you mean -32000 and 32000? This would be consistent with the motor since it has 6533 counts per revolution, and 5 revolutions would be close to where overflow occurs.

It also looks like your code follows this example found on Arduino website. On that page, they note that overflow can occur.

If you do not want it to overflow at -32768 and 32767, you might consider declaring encoderPos_2 as a long variable.

- Jeremy

Hi Jeremy,

It works well with long variable, yap it should be 32000 not 3200, sry for that.

Thanks,
RAditya