1

Is there a good way to pause the script so that add_event_detect() can listen for input? I don't like the idea of using loops so I used raw_input() to pause the script. But does raw_input() really pause the script?

And is this code resource friendly, since I am just listening for events or is there a better/right way to do this?

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def my_callback(channel):
    print("Callback on channel: ", channel)

GPIO.add_event_detect(11, GPIO.FALLING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(13, GPIO.FALLING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(15, GPIO.FALLING, callback=my_callback, bouncetime=300)

raw_input()
GPIO.cleanup()

1 Answer 1

3

You want signal.pause():

import RPi.GPIO as GPIO
from signal import pause

GPIO.setmode(GPIO.BOARD)

GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def my_callback(channel):
    print("Callback on channel: ", channel)

GPIO.add_event_detect(11, GPIO.FALLING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(13, GPIO.FALLING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(15, GPIO.FALLING, callback=my_callback, bouncetime=300)

try:
    pause()
except KeyboardInterrupt:
    GPIO.cleanup()

This is what we recommend is gpiozero. Assuming your inputs are buttons, the equivalent would be:

from gpiozero import Button
from signal import pause

btn1 = Button(11)
btn2 = Button(13)
btn3 = Button(15)

def my_callback(btn):
    print("Called by button on pin", btn.pin.number)

btn1.when_pressed = my_callback
btn2.when_pressed = my_callback
btn3.when_pressed = my_callback

pause()

Note that gpiozero provides implicit cleanup at the end of a script; buttons default to pull-up (so falling edge is paired with the button being pressed), and the btn parameter to the callback is optional.

1
  • So signal.pause() is the way to go if you want to minimize the resource usage, is that correct? Jan 28, 2021 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.