I am using the GPIO pins on my Raspberry Pi with a PIR sensor to detect motion. When the sensor detects motion I want to then move the software onto other functions.
At the moment, to detect motion I have my program constantly running in a loop while it is waiting for motion to be detected. While this works at the moment, for use in the future this will be incredibly inefficient and am hoping to improve on this by assigning it to an event.
Is there any way to bind my GPIO input to an event that is detected by the program without manually running a loop.
Here is my current loop for detection motion:
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)
The counter and detecting motion multiple times is used to reduce the number of false positives that the sensor picks up.
Raspberry-gpio-python or RPi. GPIO, is a Python module to control the GPIO interface on the Raspberry Pi. It was developed by Ben Croston and released under an MIT free software license. The project Wiki has documentation including example programs.
GPIO Library. If you code in Python, the RPi. GPIO Python library (included with Raspbian) lets you configure, read, and write to GPIO pins.
GPIO provides a built-in function GPIO. cleanup() to clean up all the ports you've used. But be very clear what this does. It only affects any ports you have set in the current program.
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 sleep import RPi.GPIO as GPIO var=1 counter = 0 GPIO.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 here while 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With