Snippets

Alexander Boden Raspberry Pi Radio Player with Rotary Encoder Control

Created by Alexander Boden

File mpc-radio.py Added

  • Ignore whitespace
  • Hide word diff
+# 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
+import atexit
+import RPi.GPIO as GPIO
+from time import sleep
+
+GPIO.setmode(GPIO.BCM)
+
+#Setup rotary encoder
+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)
+
+encoderPos = 0
+
+#Take care we exit gracefully
+def cleanup():
+	print("Exiting ...")
+	GPIO.cleanup()
+
+#Callback function when the knob moves
+def detectrotation(pin):
+	if (GPIO.input(pinA) == 0):		
+		if (GPIO.input(pinB) == 1):
+			switch(1) #Clockwise
+		else:
+			switch(0) #Counterclockwise
+
+#Switching channels
+def switch(direction):
+	global encoderPos
+	
+	client = MPDClient()
+	client.connect('localhost', 6600)
+	client.clear()
+	client.load("somafm")
+	
+	if (direction == 1): #Clockwise
+		if (encoderPos < len(client.playlistinfo())):
+			encoderPos += 1
+			client.play(encoderPos)
+			print("Now playing: " + str(client.currentsong()['file']))
+		else: 
+			print("End of playlist")
+			encoderPos = len(client.playlistinfo())
+	elif (direction == 0): #Counterclockwise
+		if (encoderPos > 0):
+			encoderPos -= 1
+			client.play(encoderPos)
+			print("Now playing: " + str(client.currentsong()['file']))
+		else: 
+			print ("End of playlist")
+			encoderPos = 0
+	else: #Resume
+		if (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 resume
+
+while True:
+	sleep(0.01)
+	
+
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.