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--;
}
}