On Sun, Nov 25, 2012 at 7:32 AM, Sean Carolan <scaro...@gmail.com> wrote:
> This is how I'm checking for a button press:

This should really be done with interrupts, but unfortunately there is
no support in the RPi.GPIO module for that, even if you have a patched
kernel.

I've done a workshop earlier this month that was on buttons with
RPi.GPIO, might be of interest:
http://raspberry-python.blogspot.com/2012/11/pyhack-workshop-01.html
http://raspberry-python.blogspot.com/2012/11/piquizmachine.html

(next workshop is on the 8th, but that'll be on the raspberry pi and motors)

Fundamentally, the loop is:

while gpio.input(PIN):
    pass
dostuff()

The moment the loop ends, the button was pressed. On the next line you
would do something, and then go back to polling. If you do have to do
something at the same time, you'll have to look into threads. Or you
could launch an external script as a background process.

Now, on to your code:
> modes = (weather, alarmclock, moodlight)
> currmode = 0
> mode = 10  ## mode button is on pin #10

mode and modes are constants. In python, it is a convention to use
caps. MODES= and MODE=
This helps readability of the code. Are weather, alarmclock

Also, I typically import RPi.GPIO as gpio (lowercase). So you would
type gpio.input(MODE). It makes more sense.

> def checkMode():

pass the current mode: def checkmode( current):

>     global currmode

That way you dont have to do the above

>     modechange = False
>     GPIO.setup(mode, GPIO.IN)

Do that outside of the function. gpio.setup() should be done once at
the beginning. It then has plenty of time to stabilise and you are not
wasting time in the function. Also, dont forget to do a gpio.cleanup()
when leaving (and possibly in a try: except: finally: block if it is
likely the program ends abruptly).

>     if GPIO.input(mode) == False:
>         print "Mode button pressed."
>         if currmode < len(modes) - 1:
>             currmode += 1
>         else:
>             currmode = 0
>         modechange = True
>     #print modes[currmode]
>     return (modes[currmode], modechange)
>
> It's pretty simple, really.  If GPIO.input(mode) returns False, then
> the button is pressed.  My function above returns the current mode
> from my modes tuple, and whether a change was detected.

The rest of your code is to support your requirement of returning a
mode and boolean value. It could be a bit tighter, but the main issue
is how you are separating the scope. The loop should be in the
function, and no sleep (or less than 50ms if you insist), else you
might miss the press.

I'm not sure if you were asking for pointers or a complete solution,
so I'll leave it at this for now.

Francois

--
pyptug.blogspot.com  -  raspberry-python.blogspot.com
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to