# 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. frommpdimportMPDClientimportatexitimportRPi.GPIOasGPIOfromtimeimportsleepGPIO.setmode(GPIO.BCM)#Setup rotary encoderpinA=24# Connect to CLKpinB=23# Connect to DATAGPIO.setup(pinA,GPIO.IN,pull_up_down=GPIO.PUD_UP)GPIO.setup(pinB,GPIO.IN,pull_up_down=GPIO.PUD_UP)encoderPos=0#Take care we exit gracefullydefcleanup():print("Exiting ...")GPIO.cleanup()#Callback function when the knob movesdefdetectrotation(pin):if(GPIO.input(pinA)==0):if(GPIO.input(pinB)==1):switch(1)#Clockwiseelse:switch(0)#Counterclockwise#Switching channelsdefswitch(direction):globalencoderPosclient=MPDClient()client.connect('localhost',6600)client.clear()client.load("somafm")if(direction==1):#Clockwiseif(encoderPos<len(client.playlistinfo())):encoderPos+=1client.play(encoderPos)print("Now playing: "+str(client.currentsong()['file']))else:print("End of playlist")encoderPos=len(client.playlistinfo())elif(direction==0):#Counterclockwiseif(encoderPos>0):encoderPos-=1client.play(encoderPos)print("Now playing: "+str(client.currentsong()['file']))else:print("End of playlist")encoderPos=0else:#Resumeif(encoderPos<len(client.playlistinfo())):print("Resuming ...")client.play(encoderPos)print("Now playing: "+str(client.currentsong()['file']))else:print("End of playlist")encoderPos=len(client.playlistinfo())client.close()client.disconnect()atexit.register(cleanup)GPIO.add_event_detect(pinA,GPIO.FALLING,callback=detectrotation,bouncetime=250)switch(-1)#Just resumewhileTrue:sleep(0.01)
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.