For my robot, I am running two 12v Motor with an Encoder from Pololu with a 29:1 gear ratio. In order to read the encoder values, I used this library (Encoder Library, for Measuring Quadarature Encoded Position or Rotation Signals) to read values to prevent the Arduino program from crashing. I essentially copy and pasted the sample code and made it into a function for my program and it worked fine. A couple of weeks later, when I get back to working with the encoders, I am getting readings on 0-1 and 1-0 every time I turn the left motor. If I flash the basic sample, both encoder values work without and issue. Is there anything that could be causing the 0-1 and 1-0 transition? I have an Arduino Mega and I tried using the other interrupt pins ((2, 3), I am currently using (18, 19) and (20, 21)). Here is the code for the function that is called in loop():
/* Encoder Library - TwoKnobs Example
* http://www.pjrc.com/teensy/td_libs_Encoder.html
*
* This example code is in the public domain.
*/
#include <Encoder.h>
// Change these pin numbers to the pins connected to your encoder.
// Best Performance: both pins have interrupt capability
// Good Performance: only the first pin has interrupt capability
// Low Performance: neither pin has interrupt capability
Encoder knobLeft(18, 19);
Encoder knobRight(20, 21);
// avoid using pins with LEDs attached
void setup() {
Serial.begin(9600);
Serial.println("TwoKnobs Encoder Test:");
}
long positionLeft = -999;
long positionRight = -999;
void loop() {
long newLeft, newRight;
newLeft = knobLeft.read();
newRight = knobRight.read();
if (newLeft != positionLeft || newRight != positionRight) {
Serial.print("Left = ");
Serial.print(newLeft);
Serial.print(", Right = ");
Serial.print(newRight);
Serial.println();
positionLeft = newLeft;
positionRight = newRight;
}
// if a character is sent from the serial monitor,
// reset both back to zero.
if (Serial.available()) {
Serial.read();
Serial.println("Reset both knobs to zero");
knobLeft.write(0);
knobRight.write(0);
}
}
When I swap (18,19) with (20,21), only the variable knobRight is reading correctly so I know it isn't an issue with the encoders themselves. Any help on what could be causing this issue would be greatly appreciated. Thanks.