Python is the most efficient way to wait for input

I have a python program that I want to run in the background (on a raspberry Pi), which waits for GPIO input, then performs an action and continues to wait for input until the process is killed.

What is the most effective way to achieve this. I understand that using while truth is not so effective. Ideally, it would use interrupts - and I could use GPIO.wait_for_edge - but it should have been in some kind of loop or continuation of work after the handler has finished.

thanks

+5
source share
2 answers

According to this: http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio GPIO.wait_for_edge (23, GPIO.FALLING) will wait for the transition to output 23 instead of interrupting the survey. It will continue only when triggered. You can wrap it in try: / except KeyboardInterrupt to catch ctrl-c.

If you want to continue processing, you need to register a callback function for your interrupt. See: http://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/

def callback(channel): do something here GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback) continue your program here, likely in some sort of state machine 
+1
source

I understand that when you say โ€œusing while the truthโ€, you mean a survey that checks the state of gpio at a certain time interval to detect changes, due to some processing time.

One option to avoid polling (from docs ) is wait_for_edge ():

The wait_for_edge () function is designed to block the execution of your program until an edge is detected.

It seems that you are looking for; the program will be suspended execution using epool () IIUC.

Now suppose you meant that you did not want to use GPIO.wait_for_edge () because you did not want to lose GPIO state changes during event processing, you would need to use threads. One possible solution is Queue events and customization:

  • One thread for while True: queue.put(GPIO.wait_for_edge(...)) .
  • Another thread to execute Queue.get() .
+1
source

All Articles