Saturday, October 02, 2021

Raspberry rotary encoder in Python

 Nothing fancy here, just an adaptation of the code in here to add the switch function in the rotary encoder software.

Connections are like this:


Output will be "UP", "Down" an "click" messages depending on the rotary encoder change, you can then re-use for your own code inside the functions.


I'm using it now to control an SDR receiver (rtl_sdr), might post about it when finished.

The code after the change is this one:

##############

import RPi.GPIO as GPIO
from time import sleep
 
counter = 10
 
Enc_A = 17 
Enc_B = 27 
Enc_SW = 22
 
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.setup(Enc_SW, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.add_event_detect(Enc_A, GPIO.RISING, callback=rotation_decode, bouncetime=10)
    GPIO.add_event_detect(Enc_SW, GPIO.FALLING, callback=swClicked, bouncetime=300)
    return


def swClicked(channel):
#        global paused
#        paused = not paused
        print ("click")  
 
 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
        print "UP"
        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
        print "DOWN"
        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()

##############

As you can see side by side, only some extra lines, all credit to the original code creator.



Have a nice day!

No comments: