I meant how do I turn a button into a switch?
from gpiozero import LED, Button
led = LED(25)
button = Button(2)
while True : # otherwise the script will only work once
button.wait_for_press()
led.toggle()
button.wait_for_release()
So I need 2 sequences to turn it off and on
Example 1: toggle state with functions (stays on or off)
from gpiozero import LED, Button
led = LED(25) # GPIO 25
ledState= 0
button = Button(2) # GPIO 2
def on():
led.on() # Since Python doesn't have function-enclosing parentheses, here are 4 spacebars to assign the contents to the function.
def off():
led.off()
while True : # otherwise the script will only work once
button.wait_for_press()
if ledState == 0:
on()
ledState = 1
button.wait_for_release() # wait or otherwise the script will trigger again while the button is still pressed
continue # stop the current loop iteration here and start again
if ledState == 1: # alternative: if not ledState == 0: or else:
off()
ledState = 0
button.wait_for_release()
Example 2: toggle state with functions (led is on, only while button is pressed)
from gpiozero import LED, Button
led = LED(25) # GPIO 25
ledState= 0
button = Button(2) # GPIO 2
def on():
led.on() # Since Python doesn't have function-enclosing parentheses, here are 4 spacebars to assign the contents to the function.
def off():
led.off()
while True : # otherwise the script will only work once
button.wait_for_press()
on()
button.wait_for_release()
off()
Example 3 using functions and "when_pressed" && "when_released"
Useful link: https://gpiozero.readthedocs.io/en/stable/faq.html
from gpiozero import LED, Button
from signal import pause
led = LED(25) # GPIO 25
button = Button(2) # GPIO 2
def on():
led.on() # Since Python doesn't have function-enclosing parentheses, here are 4 spacebars to assign the contents to the function.
def off():
led.off()
button.when_pressed = on # Contrary to expectations, there should be no parentheses after the function call
button.when_released = off
pause() # prevents the script from stopping after it read through everything. The pause function enables the script to keep on listening for button presses