I'm using these optical encoders to keep track of the wheel turns on a robot. I've attached the two hardware interrupts on the Uno to each encoder to count the ticks. However, while INT1 is giving stable, consistent readings, INT0 is giving erratic and noisy results. My code is below, as well as a screenshot of the serial monitor showing the inconsistency.
I've tried replacing the encoders, with no luck. I'm quite sure the problem is the INT0 interrupt. I've also tried using pullup resistors. I've considered using PinChangeInt, but I'm also using SoftwareSerial and the two are incompatible. Any suggestions? Am I missing something obvious here?
#define rightTireInterrupt INT0
#define leftTireInterrupt INT1
#define rightEncPin 2
#define leftEncPin 3
#define leftEncPower 4
#define rightEncPower 5
volatile int leftTick = 0;
volatile int rightTick = 0;
char printBuffer[100];
void handleRightTireInterrupt() {
rightTick ++;
}
void handleLeftTireInterrupt() {
leftTick ++;
}
void setup() {
Serial.begin(9600);
attachInterrupt(rightTireInterrupt, handleRightTireInterrupt, FALLING);
attachInterrupt(leftTireInterrupt, handleLeftTireInterrupt, FALLING);
pinMode(leftEncPower, OUTPUT); //I've run out of 5v pins, so high signals on these pins provide power to the encoders
pinMode(rightEncPower, OUTPUT);
pinMode(rightEncPin, INPUT_PULLUP);
pinMode(leftEncPin, INPUT_PULLUP);
digitalWrite(leftEncPower, HIGH);
digitalWrite(rightEncPower, HIGH);
}
void loop() {
sprintf(printBuffer, "Left Encoder: %d Right Encoder: %d", leftTick, rightTick);
Serial.println(printBuffer);
}
Sorry, I should have clarified. The numbers there result after the robot drives forward a short distance (i.e. 12 encoder ticks). INT0 is being triggered exponentially more times, while INT1 is reading accurately
When Serial.println blocks waiting for the UART interrupt service routine to empty the transmit buffer that code will deadlock (your board will lock up).