[Tutor] Python GPIO Code Help Needed

Anish Tambe anish.tambe.lists at gmail.com
Sun Oct 26 10:36:13 CET 2014


On Sun, Oct 26, 2014 at 6:35 AM, Bill Bright <wcb_rlb at bellsouth.net> wrote:

> I have been working on a piece of code that I got from another tutorial.
> The code polls the GPIO pins on a Raspberry Pi. When it detects a switch
> being flipped, it plays a corresponding audio file. My problem is, if the
> switch remains flipped, the audio repeats again and again. What I would
> like to do is when a switch is flipped have the audio play, then have the
> code pause until the switch is returned to normal (not repeating the
> audio), and then return to the while loop to poll for the next switch flip.
> I am apparently not smart enough to figure out the correct code. I really
> need some help with this and I would appreciate any assistance.
>
> Here is the code I'm working with.
>
> #!/usr/bin/env python
> from time import sleep
> import os
> import RPi.GPIO as GPIO
> GPIO.setmode(GPIO.BCM)
> GPIO.setup(23, GPIO.IN)
> GPIO.setup(24, GPIO.IN)
> GPIO.setup(25, GPIO.IN)
> while True:
>         if ( GPIO.input(23) == False ):
>                 os.system('mpg321 -g 95 a.mp3')
>         if ( GPIO.input(24) == False ):
>                 os.system('mpg321 -g 95 b.mp3')
>         if ( GPIO.input(25)== False ):
>                 os.system('mpg321 -g 95 c.mp3')
>         sleep(1.1);
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Using callbacks instead of polling might help.

You can do something like this -

def play(channel) :
    #your action here
    if channel == 23 :
        os.system('mpg321 -g 95 a.mp3')

GPIO.add_event_detect(23, GPIO.RISING, callback=play)

and similarly for the other pins.

Check the "Events and Callback Functions" section of this tutorial -
http://makezine.com/projects/tutorial-raspberry-pi-gpio-pins-and-python/

Cheers,
Anish Tambe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141026/c63711f8/attachment.html>


More information about the Tutor mailing list