waqask64
Posts: 4
Joined: Thu Jan 21, 2016 3:16 pm

Whats wrong with my code?

Thu Jan 21, 2016 3:29 pm

only the led will work when the button is pressed. the buzzer does nothing

from gpiozero import LED, Button, Buzzer
from signal import pause

led = LED(17)
button = Button(2)
buzzer = Buzzer(21)

button.when_pressed = buzzer.on
button.when_pressed = led.on
button.when_pressed = buzzer.on
button.when_pressed = buzzer.off

pause()

sprinkmeier
Posts: 410
Joined: Mon Feb 04, 2013 10:48 am
Contact: Website

Re: Whats wrong with my code?

Fri Jan 22, 2016 12:31 am

I'm guessing that the
button.when_pressed
is a simple function pointer, so assigning multiple things to it just makes the last one win.

try something like this:

Code: Select all

def foo():
    buzzer.on()
    led.on()

button.when_pressed = foo
just to check.... does the buzzer/LED work as expected when you just call the on/off functions directly?

waqask64
Posts: 4
Joined: Thu Jan 21, 2016 3:16 pm

Re: Whats wrong with my code?

Fri Jan 22, 2016 7:13 am

Yes it works when i jus activate them individually

User avatar
PeterO
Posts: 5880
Joined: Sun Jul 22, 2012 4:14 pm

Re: Whats wrong with my code?

Fri Jan 22, 2016 8:08 am

What is wrong is that you don't seem to understand how callbacks work.
Try this to start with....

Code: Select all

from gpiozero import  Buzzer
from signal import pause


buzzer = Buzzer(21)

button.when_pressed = buzzer.on
button.when_released = buzzer.off

pause()
Note: The above code is untested.

Then take sprinkmeier's suggestion and put all the "pressed" handling code into one function and all the "released" handling code into another function and set these functions as the "when_pressed" and "when_released" handlers.

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

Return to “Troubleshooting”