Skip to content

Instantly share code, notes, and snippets.

@m0xpd
Created January 17, 2013 19:29
Show Gist options
  • Save m0xpd/4558875 to your computer and use it in GitHub Desktop.
Save m0xpd/4558875 to your computer and use it in GitHub Desktop.
RPi Simple Rotary Encoder Read on GPIO
#!/usr/local/bin/python
# m0xpd
# shack.nasties 'at Gee Male dot com'
import RPi.GPIO as GPIO
# setup GPIO options...
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# setup IO bits...
GPIO.setup(12, GPIO.IN) # PinA is on GPIO 12
GPIO.setup(16, GPIO.IN) # PinB is on GPIO 16
# check initial state...
oldPinA = GPIO.input(12)
Position = 0
inc = 5 # increment
REmax = 127 # Max value
REmin = 0 # Min value
# Main Operating Loop...
while True:
encoderPinA=GPIO.input(12)
encoderPinB=GPIO.input(16)
if (encoderPinA == True) and (oldPinA == False): # Detect "upward" transition on PinA
if (encoderPinB == False): # if PinB is low...
Position=Position+inc # we're going clokwise
if Position > REmax: # limit max value
Position = REmax
else: # otherwise...
Position=Position-inc # we're going anti-clockwise
if Position < REmin: # limit min value
Position = REmin
print Position
oldPinA=encoderPinA # save current value for next time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment