Python Forum

Full Version: gpiozero button turn off LED that is already on
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a Raspberry Pi on my desk. It is wired to an LED and a button. My phone sends an SSH to the Pi when it gets a text message. The SSH runs this script to turn the LED on:

from gpiozero import LED import time from time import sleep pink = LED(20) pink.on() sleep(900)
The "sleep(900)" keeps the LED on for 15 minutes. I also have a function on my phone that sends an SSH to the same Pi to run this script, effectively cancelling the LED.

from gpiozero import LED import time from time import sleep pink = LED(20) pink.off()
What I want is to press a button connected to GPIO17 that either turns the LED off or runs the script to cancel the LED. I have tried this, but it does not work:

from gpiozero import LED, Button from signal import pause led = LED(20) button = Button(17) button.when_pressed = led.off pause()
I have confirmed that the button is open when relaxed, closed when pressed. I have confirmed that GPIO17 does function as a button, the LED does turn on and off by other means. I just can't get the button to turn it off.
You could use the toggle-method. One press => LED on, next press => LED off, next LED on

try following:
from gpiozero import LED, Button from signal import pause led = LED(20) button = Button(17) button.when_pressed = led.toggle pause()
It works to toggle the LED when running that script. While it was still running, I ran the script to turn on the LED then went back to your solution. The button had no effect (stayed on). Then I ran the script to stop the LED and went back to your solution. Then yours did not toggle the LED - it stayed off.
I was offered this solution in another forum. It replaces the script that turns on the LED and incorporates a button to turn it off. This works!

from gpiozero import LED, Button import time from time import sleep pink = LED(20) pink.on() button = Button(7) now = time.time() while time.time() < now + 900:	if button.is_pressed:	break	sleep(0.2) pink.off()