This question is regarding a project using an Arduino Uno.
I have one of these quadrature rotary encoders.
I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.
My version of the code on pastebin - I modified to use different pins for the Uno and a single encoder:
#include <digitalWriteFast.h> // library for high performance reads and writes by jrraines
#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3
volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;
void setup()
{
Serial.begin(115200);
pinMode(c_LeftEncoderPinA, INPUT);
digitalWrite(c_LeftEncoderPinA, LOW);
pinMode(c_LeftEncoderPinB, INPUT);
digitalWrite(c_LeftEncoderPinB, LOW);
attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}
// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
_LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB); // read the input pin
_LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}
void loop()
{
Serial.print(_LeftEncoderTicks);
Serial.print("\n");
delay(20);
}
I am attaching output A of the encoder to pin 2 and output B to pin 3.
This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying c_LeftEncoderPinB
accordingly).
I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).