1
votes

I'm fairly new to programming and have recently been playing around with my raspberry Pi, using the GPIO pins and some buttons to perform various actions when pressed. There's just one thing that I just can't seem to accept when creating a "listener" for the buttons.

According to everything I've been able to gather online, basically you must stick your program in an infinite loop in order to listen for button interactions, for example:

while True:
     if GPIO.input(10) == GPIO.HIGH:
          print("Button is pressed")
     else:
          print("Button is not pressed")

It just seems like it would be somewhat intensive to leave the program running constantly like that in an infinite loop, just waiting for a button to be pressed. When I run this same code on my Mac, for example, it only takes about 30 seconds before the fans kick it and it causes the computer to heat up. So my question is (hopefully this isn't too dumb of a question and is appropriate for this channel): is this a standard way for computers and programs to listen for button interactions? And is there a better, more efficient way for button events to be listened to? I've tried searching for more information on this elsewhere, but haven't been able to find anything (that I can understand at least).

2
A simple thing I have down is just a call to time.sleep in the loop. Make the sleep time a small fraction of a second. That said I'd love to hear other ideas about this. The program I wrote had a run loop like this and each time through would scan through all of the controls I cared about. - Brad Campbell

2 Answers

1
votes

I don't know the specifics on RaspberryPI, however on Arduino, 2 pins are able to trigger interrupts when the state changes.

An interrupt is an hardware thing that interrupts whatever the computer is doing to jump there. For example timers or data received on the network are interrupts, so they wake up a sleeping processor.

They are handled at a lower level, but you want to set a function that runs when the interrupt is generated. See this article https://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio-part-3

1
votes

There are better (or at least different) ways, one such approach uses what are called callbacks. There is a fairly good tutorial with some example code here.