Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reading one Rotary Encoder from a Raspberry Pi with Processing 3
/*
Reading one Rotary Encoder from a Raspberry Pi
Translated from C to Processing by Heracles Papatheodorou
via http://theatticlight.net/posts/Reading-a-Rotary-Encoder-from-a-Raspberry-Pi/
GND MIDDLE encoder leg
GPIO22 GPIO23 LEFT and RIGHT legs
3.3V LEFT and RIGHT, splits to two 10k resistors for pull-up
Processing doesn't support pull-ups, hardware pull-up required:
https://learn.adafruit.com/processing-on-the-raspberry-pi-and-pitft/hardware-io
https://learn.sparkfun.com/tutorials/pull-up-resistors/what-is-a-pull-up-resistor
Processing reference:
https://github.com/processing/processing/wiki/Raspberry-Pi
https://processing.org/reference/libraries/io/index.html
Reading rotary encoders on the RaspPi:
http://theatticlight.net/posts/Reading-a-Rotary-Encoder-from-a-Raspberry-Pi/
https://projects.drogon.net/raspberry-pi/wiringpi/functions/
*/
import processing.io.*; // import the hardware IO library
int pin_a = 22;
int pin_b = 23;
long value = 0;
int lastEncoded = 0;
void setup() {
noCursor();
GPIO.pinMode(pin_a, GPIO.INPUT);
GPIO.pinMode(pin_b, GPIO.INPUT);
//pullUpDnControl(pin_a, PUD_UP); //Processing doesn't support pull-ups so far
//pullUpDnControl(pin_b, PUD_UP);
GPIO.attachInterrupt(pin_a, this, "updateEncoder", GPIO.CHANGE);
GPIO.attachInterrupt(pin_b, this, "updateEncoder", GPIO.CHANGE);
}
void draw() {
}
void updateEncoder(int pin) {
int MSB = GPIO.digitalRead(pin_a);
int LSB = GPIO.digitalRead(pin_b);
int encoded = (MSB << 1) | LSB;
int sum = (lastEncoded << 2) | encoded;
if (sum == unbinary("1101") || sum == unbinary("0100") || sum == unbinary("0010") || sum == unbinary("1011")) {
value++;
}
if (sum == unbinary("1110") || sum == unbinary("0111") || sum == unbinary("0001") || sum == unbinary("1000")) {
value--;
}
lastEncoded = encoded;
println(value); //DEBUG
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.