pythonraspberry-pi3gpiozero

How do I detect a gpiozero Button press while in a function called by another button?


I need to trigger a relay from a Button press and wait for a signal then release the relay. In the sample code below, that signal is b2. I'm new to Python and the Pi but having fun! :)

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
from gpiozero import Button
from signal import pause
import time

def first_button():
    print("First Pressed")
    while True: #do stuff...
        time.sleep(1)
        print("waiting...")

def second_button():
    print("Second Pressed")

b1 = Button(23)
b1.when_pressed = first_button
b2 = Button(24)
b2.when_pressed = second_button

pause()

How do I detect a button press while an existing function called by a Button is still running?


Solution

  • In this solution you only switch the output on and off

    from gpiozero import Button
    from signal import pause
    import time
    
    pin = #Set a pin
    r = LED(pin)
    b1 = Button(23)
    b1.when_pressed = r.on
    b2 = Button(24)
    b2.when_pressed = r.off
    
    pause()
    

    Here a thread is started to do stuff:

    from gpiozero import Button
    from signal import pause
    import time
    import _thread
    
    run = False
    def do_stuff():
        while run: #do stuff...
            time.sleep(1)
            print("waiting...")
    
    def first_button():
        global run
        print("First Pressed")
        run = True
        _thread.start_new_thread(do_stuff)
        
    
    def second_button():
        global run
        print("Second Pressed")
        run = False
    
    b1 = Button(23)
    b1.when_pressed = first_button
    b2 = Button(24)
    b2.when_pressed = second_button
    
    pause()