You want to trigger some action in Python when movement is detected.
Use a PIR (passive infrared) motion detector module.
To make this recipe, you will need:
• Female-to-female jumper wires (see “Prototyping Equipment” on page 380)
• PIR motion detector module (see “Modules” on page 381)
Figure 11-13 shows how the sensor module is wired. This module expects a power supply of 5V and has an output of 3.3V, making it ideal for use with a Raspberry Pi.
Make sure that the PIR module you use has a 3.3V output. If it has 5V output, you will need to use a pair of resistors to reduce this to 3.3V (see Recipe 8.12).
Open an editor (nano or IDLE) and paste in the following code. As with all the program examples in this book, you can also download the program from the Code section of the Raspberry Pi Cookbook website, where it is called pir.py.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) while True: input_state = GPIO.input(18) if input_state == True: print(‘Motion Detected’) time.sleep(1) |
The program simply prints out the state of the GPIO input 18.
$ sudo python pir.py Motion Detected Motion Detected |
Discussion
Once triggered, the output of the PIR sensor will stay high for a little while. You can adjust this using one of the trimpots on its circuit board.
See Also
You could combine this recipe with Recipe 7.15 to send an email when an intruder is detected.
Table A-3. Prototyping equipment | |
Description | Suppliers |
M-M jumper wires | SparkFun: PRT-08431, Adafruit: 759 |
M-F jumper wires | SparkFun: PRT-09140, Adafruit: 825 |
F-F jumper wires | SparkFun: PRT-08430, Adafruit: 794 |
Half-sized breadboard | SparkFun: PRT-09567 Adafruit: 64 |
Pi Cobbler | Adafruit: 1105 |
Table A-9. Miscellaneous | |
1200mAh LiPo battery | Adafruit: 258 |
5V relay | SparkFun: COM-00100 |
5V panel meter | SparkFun: TOL-10285 |
Servo motor | SparkFun: ROB-09065, Adafruit: 1449 |
5V 1A power supply | Adafruit: 276 |
Low power 6V DC motor | Adafruit: 711 |
0.1 inch header pins | SparkFun: PRT-00116, Adafruit: 392 |
5 V 5-pin unipolar stepper motor | Adafruit: 858 |
12 V, 4-pin bipolar stepper motor | Adafruit: 324 |
Magician chassis with gearmotors | SparkFun: ROB-10825 |
Tactile push switch | SparkFun: COM-00097, Adafruit: 504 |
Miniature slide switch | SparkFun: COM-09609, Adafruit: 805 |
Rotary encoder | Adafruit: 377 |
4×3 keypad | SparkFun: COM-08653 |
Piezo buzzer | SparkFun: COM-07950, Adafruit: 160 |