Skip to content

Instantly share code, notes, and snippets.

@snorfalorpagus
Created September 17, 2017 10:57
Show Gist options
  • Save snorfalorpagus/3e3b6c63b893e48d389d6bf7405625dd to your computer and use it in GitHub Desktop.
Save snorfalorpagus/3e3b6c63b893e48d389d6bf7405625dd to your computer and use it in GitHub Desktop.
Rotary encoder on Raspberry Pi
import RPi.GPIO as GPIO
import threading
GPIO.setmode(GPIO.BCM)
class RotaryEncoder:
def __init__(self, pin_a, pin_b):
self.pin_a = pin_a
self.pin_b = pin_b
self.state_a = None
self.state_b = None
self.count = 0
self.lock = threading.Lock()
GPIO.setup(pin_a, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(pin_b, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def callback(channel):
switch_a = GPIO.input(self.pin_a)
switch_b = GPIO.input(self.pin_b)
else:
if (switch_a, switch_b) == (self.state_a, self.state_b):
# nothing changed
return
# print(switch_a, switch_b)
if switch_a and switch_b:
# rotation is complete, which direction?
self.lock.acquire()
if channel == self.pin_a:
self.count += 1
else:
self.count -= 1
self.lock.release()
self.update()
GPIO.add_event_detect(self.pin_a, GPIO.BOTH, callback=callback)
GPIO.add_event_detect(self.pin_b, GPIO.BOTH, callback=callback)
def update(self):
print("count", self.count)
r = RotaryEncoder(17, 27)
if __name__ == "__main__":
try:
import time
while True:
time.sleep(1)
finally:
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment