I found some pretty simply rotary encoder code I'm trying to get working, but it's not working as expected. I based my sketch from this discussion on HiFiDuino.
I have a RGB rotary encoder from Sparkfun. I've got Encoder pin B connected to D3 and pin A to D2 and encoder pin C to ground on my Arduino Uno. When I run my sketch, I expect to see the encoder value print on the serial monitor every time the value changes, but it doesn't seem to be changing and it's not printing any encoder values. Here's my sketch:
#define ENCODER_A 2
#define ENCODER_B 3
static int encoderval = 0;
static boolean rotating = false;
void rotEncoder() {
rotating = true; // If motion is detected in the rotary encoder, set the flag to true
}
void setup() {
Serial.begin(9600);
Serial.println("Encoder test");
pinMode(ENCODER_A, INPUT);
pinMode(ENCODER_B, INPUT);
attachInterrupt(0, rotEncoder, CHANGE); // Attach Interrupt for rotary encoder
}
void loop() {
while(rotating)
{
delay(2); // debounce by waiting 2 milliseconds
if (digitalRead(ENCODER_B) == digitalRead(ENCODER_A))
{ encoderval--; } // Clockwise rotation
else
{ encoderval++; } // Counter-clockwise rotation
rotating = false; // Reset the flag
Serial.println(encoderval); // print encoder counter value
}
}