The pins are 11 and 12.
As far as the code goes, here is the code which works (but doesn't use interrupts):
const int encoder0PinA = 11;
const int encoder0PinB = 12;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int encoder0PinBLast = LOW;
void setup()
{
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
Serial.begin(9600);
}
void loop()
{
int encoder0PinANew = digitalRead(encoder0PinA);
int encoder0PinBNew = digitalRead(encoder0PinB);;
if(encoder0PinANew == encoder0PinALast
&& encoder0PinBNew == encoder0PinBLast)
{
//Serial.println(" no change");
return;
}
char chOutputBuffer[80];
sprintf(chOutputBuffer, "%4d %4d", encoder0PinANew, encoder0PinBNew);
Serial.println(chOutputBuffer);
if(encoder0PinANew != encoder0PinALast)
{
if(encoder0PinANew == encoder0PinBNew)
{
Serial.println(" increasing");
}
else
{
Serial.println(" decreasing");
}
}
else
{
if(encoder0PinANew == encoder0PinBNew)
{
Serial.println(" decreasingX");
}
else
{
Serial.println(" increasingX");
}
}
encoder0PinALast = encoder0PinANew;
encoder0PinBLast = encoder0PinBNew;
delay(500);
}
...and the code which uses interrupts (but doesn't print anything) is:
#define encoder0PinA 12
#define encoder0PinB 11
volatile unsigned int encoder0Pos = 0;
void setup()
{
pinMode(encoder0PinA, INPUT);
pinMode(encoder0PinB, INPUT);
// encoder pin on interrupt 0 (pin 12)
attachInterrupt(0, DoEncoderA, CHANGE);
// encoder pin on interrupt 1 (pin 11)
attachInterrupt(1, DoEncoderB, CHANGE);
Serial.begin(9600);
}
void loop()
{
// Do stuff here
}
void DoEncoderA()
{
// look for a low-to-high on channel A
if (digitalRead(encoder0PinA) == HIGH)
{
// Check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW)
{
encoder0Pos = encoder0Pos + 1; // CW
}
else
{
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // must be a high-to-low edge on channel A
{
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == HIGH)
{
encoder0Pos = encoder0Pos + 1; // CW
}
else
{
encoder0Pos = encoder0Pos - 1; // CCW
}
}
Serial.println (encoder0Pos, DEC);
// use for debugging - remember to comment out
}
void DoEncoderB()
{
// look for a low-to-high on channel B
if(digitalRead(encoder0PinB) == HIGH)
{
// check channel A to see which way encoder is turning
if(digitalRead(encoder0PinA) == HIGH)
{
encoder0Pos = encoder0Pos + 1; // CW
}
else
{
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // Look for a high-to-low on channel B
{
// Check channel B to see which way encoder is turning
if (digitalRead(encoder0PinA) == LOW)
{
encoder0Pos = encoder0Pos + 1; // CW
}
else
{
encoder0Pos = encoder0Pos - 1; // CCW
}
}
}
I'm new to interrupts, so I'm just starting to learn about them. The code for the second sketch was taken from the rotary encoders tutorial page. I've tried all of the different samples on the page which use interrupts, and none seem to work for me.