I just purchased this rotary encoder from digikey http://search.digikey.com/scripts/DkSearch/dksus.dll?WT.z_header=search_go&lang=en&site=ca&keywords=P12336-ND&x=0&y=0 and have been using my own variation of the rotary encoder code in the playground
/*
The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 10
* LCD D5 pin to digital pin 9
* LCD D6 pin to digital pin 8
* LCD D7 pin to digital pin 7
* Encoder A to digital pin 2
* Encoder B to digital pin 3
* Encoder Button to digital pin 4
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Encoder variables
int enc_a = 2;
int enc_b = 3;
int enc_button = 4;
int count = 0;
long prevMS = 0;
int interval = 200;
void setup() {
pinMode(enc_a, INPUT);
digitalWrite(enc_a, HIGH);
pinMode(enc_b, INPUT);
digitalWrite(enc_b, HIGH);
pinMode(enc_button, INPUT);
attachInterrupt(0, encoderPos, CHANGE);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
}
void loop() {
if (digitalRead(enc_button) == LOW) {
count = 0;
lcd.clear();
}
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0);
lcd.print(count);
//lcd.clear();
}
void encoderPos() {
if (millis() - prevMS > interval) {
prevMS = millis();
if (digitalRead(enc_a) == digitalRead(enc_b)) {
count++;
} else {
count--;
}
}
// Sets range to 0-9
if (count < 0) {
count = 9;
} else if (count > 9) {
count = 0;
}
}
While it is technically working, I'm finding the rotary encoder to be rather glitchy. If I turn it really slow (and I mean really slow) it works as intended, but turning it at a natural speed I'm finding my count sometimes goes up, when it should go down and vice-versa - but only for one or two counts, so instead of outputting 1, 2, 3, 4, 5, I'll get 1, 2, 3, 2, 3, 4, 5, 3, 4, 5.
Is there a problem with my code, or is it simply because I bought a $2 rotary encoder?