Skip to content

Instantly share code, notes, and snippets.

@Arty2
Created February 22, 2016 03:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Arty2/ab77038addb7f40163ba to your computer and use it in GitHub Desktop.
Save Arty2/ab77038addb7f40163ba to your computer and use it in GitHub Desktop.
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