The examples I see for the GPIO input are based on a loop which waits and check if the GPIO is receiving any info. Is there a way of just detecting when a button was pressed without using a loop under the hood? I mean, something like, call this function immediatelly after receiving an input at the GPIO.
1 Answer
That's exactly what interrupts do. In python there is a function RPi.GPIO.add_event_detect( GPIO_NUMBER, GPIO.RISING, callback=yourCallback)
. You then need to define a function yourCallback()
where you manage whatever has to happen when the respective gpio senses a RISING edge. A websearch for "raspberry pi gpio interrupt" will reveal several detailed tutorials about that topic.
You still should mind debouncing the button.
-
I vaguely remember that Rpi.GPIO is very newbie considerate and debounces by hardware or software (I forgot which) without newbies even knowing what is the meaning of button bouncing. I remember this well because once I thought I was clever and tried to do debouncing by both hardware and software, but found I wasted time, because Rpi.GPIO always debounces by default. However I am only 80% sure that I remember things correctly.– tlfong01Commented Jun 8, 2019 at 0:53