0

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?

Tim Duncklee
  • 1,420
  • 1
  • 23
  • 35

1 Answers1

1

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()
ben_nuttall
  • 859
  • 10
  • 20
NWiogrhkt
  • 113
  • 1
  • 9
  • This makes sense although it appears _thread has been replaced with threading module so I'll need to change the code to run it. "ImportError: No module named _thread" – Tim Duncklee Sep 13 '20 at 14:59
  • What version are you running? Before 3.7 it is a optional module https://docs.python.org/3/library/_thread.html – NWiogrhkt Sep 13 '20 at 18:55