Skip to content

Instantly share code, notes, and snippets.

@yuma-m
Created February 14, 2016 10:09
Show Gist options
  • Save yuma-m/5a481fe7e914d24ac5ea to your computer and use it in GitHub Desktop.
Save yuma-m/5a481fe7e914d24ac5ea to your computer and use it in GitHub Desktop.
Play song when switch connected to GPIO is pushed
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import RPi.GPIO as GPIO
import os
import time
import random
import shlex
import subprocess
# Pin Number
PIN = 19
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
last_pin_status = 0
SONG_DIR = '/home/pi/Music/'
SONG_LIST = ['song01.wav', 'song02.wav', 'song03.wav']
def play_song():
song = random.choice(SONG_LIST)
song_path = os.path.join(SONG_DIR, song)
command = 'aplay %s' % (song_path)
print(command)
subprocess.Popen(shlex.split(command))
while True:
pin_status = GPIO.input(PIN)
if last_pin_status == 1 and pin_status == 0:
play_song()
last_pin_status = pin_status
time.sleep(0.1)
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment