Raspberry Pi- GPIO Events in Python
The RPi.GPIO Python library now supports Events, which are explained in the Interrupts and Edge detection paragraph.
So after updating your Raspberry Pi with sudo rpi-update
to get the latest version of the library, you can change your code to:
from time import sleepimport RPi.GPIO as GPIOvar=1counter = 0GPIO.setmode(GPIO.BOARD)GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)def my_callback(channel): if var == 1: sleep(1.5) # confirm the movement by waiting 1.5 sec if GPIO.input(7): # and check again the input print("Movement!") captureImage() # stop detection for 20 sec GPIO.remove_event_detect(7) sleep(20) GPIO.add_event_detect(7, GPIO.RISING, callback=my_callback, bouncetime=300)GPIO.add_event_detect(7, GPIO.RISING, callback=my_callback, bouncetime=300)# you can continue doing other stuff herewhile True: pass
I chose the Threaded callbacks method because I suppose that your program does some other things in parallel to change the value of var
.
Now the RPi GPIO library has inbuilt interrupt driven GPIO control which can happen in separate thread freeing up resources.You may wish to read the following http://raspi.tv/2013/how-to-use-interrupts-with-python-on-the-raspberry-pi-and-rpi-gpio-part-3
You could wrap the GPIO-code into it's own thread and have the rest of your program do something else while the GPIO is waiting for input. Check out the threading module
First I'd wrap your code into a function
def wait_input(): var=1 counter = 0 while var == 1: if GPIO.input(7): counter += 1 time.sleep(0.5) else: counter = 0 time.sleep(1) if counter >= 3: print "Movement!" captureImage() time.sleep(20)
And then in your main program you could something like this
input_thread = threading.Thread(target = wait_input)input_thread.start()# do something in the meanwhileinput_thread.join()
There are plenty of questions on SO concerning python threading, so you might want to dig them up. Please note that there are also plenty of things to consider when using threads, especially in python which has a global interpreter lock (GIL) which allows only one process to run at a time. It might also be smart to check out the multiprocessing module with which one can route around the GIL.