Skip to content

Instantly share code, notes, and snippets.

@dzindra
Last active May 23, 2017 10:42
Show Gist options
  • Save dzindra/d8ac3c4968e72e590b84f1fbd949ef48 to your computer and use it in GitHub Desktop.
Save dzindra/d8ac3c4968e72e590b84f1fbd949ef48 to your computer and use it in GitHub Desktop.
Simple push button controlled song player for Raspberry Pi
#!/usr/bin/env python
import sys
import RPi.GPIO as GPIO
import signal
import subprocess
from time import sleep
pinOutput = 12
pinInput = 16
soundFile = "/home/pi/player/music.mp3"
discoRunning = False
def log(message):
sys.stdout.write(message + "\n")
sys.stdout.flush()
def handleButton(channel):
global discoRunning
if discoRunning:
discoRunning = False
else:
discoRunning = True
def executeDisco():
global discoRunning
log("Executing disco")
GPIO.output(pinOutput, GPIO.HIGH)
p = subprocess.Popen(["mpg123", "-q", soundFile])
while p.poll() is None:
sleep(0.1)
if discoRunning == False:
log("Terminating disco by button")
p.terminate()
sleep(0.1)
GPIO.output(pinOutput, GPIO.LOW)
log("Finishing disco")
def shutdown(signum, frame):
log("Quitting")
GPIO.cleanup()
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pinOutput, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(pinInput, GPIO.IN, pull_up_down=GPIO.PUD_UP)
log("Ready and sleeping")
sleep(3)
GPIO.add_event_detect(pinInput, GPIO.RISING, callback=handleButton, bouncetime=500)
log("Button prepared")
while True:
if discoRunning:
executeDisco()
discoRunning = False
sleep(0.05)
[Unit]
Description=Push button player
After=network.target sound.target
[Service]
ExecStart=/home/pi/player/player.py
KillMode=process
Restart=on-failure
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment