Raspberry PI Rotary Encoder Control Code

Rotary encoders are designed for infinite circular turns in both direction. You can press the top button to send out an extra event. Encoders can sense if they are turned in full, half or quarter rounds depending on the type of the encoder. They send out these turns in bit arrays. To see the prompt bit arrays you should receive, please check the datasheet of the encoder you are using. You can find datasheets on the internet. When the rotary encoder is turned by someone or the button is pressed an event is sent from the device.

Required hardware

  • Raspberry PI
  • Rotary encoder
  • 3 Resistors 1kΩ

Source code to install on controller


import RPi.GPIO as GPIO
from time import sleep

counter = 10

Enc_A = 17  
Enc_B = 27  


def init():
    print "Rotary Encoder Test Program"
    GPIO.setwarnings(True)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(Enc_A, GPIO.IN)
    GPIO.setup(Enc_B, GPIO.IN)
    GPIO.add_event_detect(Enc_A, GPIO.RISING, callback=rotation_decode, bouncetime=10)
    return


def rotation_decode(Enc_A):
    global counter
    sleep(0.002)
    Switch_A = GPIO.input(Enc_A)
    Switch_B = GPIO.input(Enc_B)

    if (Switch_A == 1) and (Switch_B == 0):
        counter += 1
        print "direction -> ", counter
        while Switch_B == 0:
            Switch_B = GPIO.input(Enc_B)
        while Switch_B == 1:
            Switch_B = GPIO.input(Enc_B)
        return

    elif (Switch_A == 1) and (Switch_B == 1):
        counter -= 1
        print "direction <- ", counter
        while Switch_A == 1:
            Switch_A = GPIO.input(Enc_A)
        return
    else:
        return

def main():
    try:
        init()
        while True :
            sleep(1)

    except KeyboardInterrupt:
        GPIO.cleanup()

if __name__ == '__main__':
    main()

More information