This is an example Python2 script for a hardware Play/Pause button using an mpc toggle command. It may seem a little long, because it includes some step-by-step directions, but the actual script is just four lines of code. The rest is just overhead.
This is the code I used to test a hardware play/pause function and the momentary push button shown in the pics above. It requires one momentary switch, connected to the Pi 40-pin header with two jumpers.
The script toggles play/pause once, when a button connected to header pin 7 (GPIO4) is pressed.
(the example assumes that python2 is already installed).
Directions:
Open an empty file in the editor, paste the example below into the file, and save the file.
- Code: Select all
nano hw_pause_play.py
- Code: Select all
#!/usr/bin/env python2
import RPi.GPIO as GPIO
import subprocess
GPIO.setmode(GPIO.BOARD)
#Select an unused GPIO header pin as input
InputPin = 7
# Set pin to input, and enable internal pull-up
GPIO.setup(InputPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Wait for a button press on the selected pin (pin pulled to ground, falling edge)
GPIO.wait_for_edge(InputPin, GPIO.FALLING)
# When pressed, execute the mpc toggle command:
print "*** Button press detected ***" # (print statement added for debugging)
subprocess.call("mpc toggle", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Make the file executable using chmod +x:
- Code: Select all
chmod +x hw_pause_play.py
The new script can now be tested from the command line:
- Code: Select all
python2 hw_pause_play.py
If you are satisfied it does what you want, save or copy the file to its permanent location
- Code: Select all
cp hw_pause_play.py /var/www/command/
...and make sure it is executable in the new location!
- Code: Select all
chmod +x /var/www/command/hw_pause_play.py