[Tutor] Python GPIO Code Help Needed

Dave Angel davea at davea.name
Sun Oct 26 13:27:59 CET 2014


Bill Bright <wcb_rlb at bellsouth.net> Wrote in message:
> 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
> 
> 

So what you're saying is that you want t do an action anytime you
 notice a change in the input state from True to False.  So you
 just need to store the old state in your own variable. Whever old
 is True and new is False, perform the action.

In your initialization, create a new list of bools, length at least 26.
    oldstates = [True] * 32

Now write a function changed, that detects the state change for
 one of the inputs :

def changed(num):
    newstate = GPIO.input(num)
    change = oldstates[num] and not newstate
    oldstates[num] = newstate
    return change

Now each of the if clauses can be written :

      if changed(23):
           os.system....

Hopefully this will give you some ideas how you could generalize
 and/or streamline the code. If you decide to use more than 3
 switches, or if some want to detect the opposite transition, or
 ...


-- 
DaveA



More information about the Tutor mailing list