+# For running this code you need a working MPD installation (set the right address and port in the switch function) as well as a KY-40 or similar rotary encoder connected to the right pins on your Raspberry Pi.
+from mpd import MPDClient
+pinA = 24 # Connect to CLK
+pinB = 23 # Connect to DATA
+GPIO.setup(pinA, GPIO.IN, pull_up_down = GPIO.PUD_UP)
+GPIO.setup(pinB, GPIO.IN, pull_up_down = GPIO.PUD_UP)
+#Take care we exit gracefully
+#Callback function when the knob moves
+def detectrotation(pin):
+ if (GPIO.input(pinA) == 0):
+ if (GPIO.input(pinB) == 1):
+ switch(0) #Counterclockwise
+ client.connect('localhost', 6600)
+ if (direction == 1): #Clockwise
+ if (encoderPos < len(client.playlistinfo())):
+ client.play(encoderPos)
+ print("Now playing: " + str(client.currentsong()['file']))
+ print("End of playlist")
+ encoderPos = len(client.playlistinfo())
+ elif (direction == 0): #Counterclockwise
+ client.play(encoderPos)
+ print("Now playing: " + str(client.currentsong()['file']))
+ print ("End of playlist")
+ if (encoderPos < len(client.playlistinfo())):
+ client.play(encoderPos)
+ print("Now playing: " + str(client.currentsong()['file']))
+ print("End of playlist")
+ encoderPos = len(client.playlistinfo())
+atexit.register(cleanup)
+GPIO.add_event_detect(pinA, GPIO.FALLING, callback=detectrotation, bouncetime=250)