- Sat Jan 31, 2009 6:36 pm
#65052
I recently got this rotary encoder for use in a project I'm working on. Here's some simple code to make it count up and down when you turn it clockwise or counter-clockwise.
Code: Select all
The encoder is connected to digital pins 5,6 and 7 on the Arduino. This will just output the count to the serial port, which can be monitored from the Arduino GUI.int state, prevstate = 0, count = 0;
int nextEncoderState[4] = { 2, 0, 3, 1 };
int prevEncoderState[4] = { 1, 3, 0, 2 };
void setup()
{
pinMode(7, INPUT);
pinMode(5, INPUT);
pinMode(6, OUTPUT);
digitalWrite(6, LOW);
digitalWrite(5, HIGH);
digitalWrite(7, HIGH);
Serial.begin(9600);
}
void loop()
{
state = (digitalRead(7) << 1) | digitalRead(5);
if (state != prevstate) {
if (state == nextEncoderState[prevstate]) {
count++;
} else if (state == prevEncoderState[prevstate]) {
count--;
}
Serial.println(count, DEC);
prevstate = state;
}
}
[url=http://www.geekandproud.net/store/]FFC/FPC breakout board[/url]