Use the Python programming language to write code that will detect movement and print out text to warn the user.
You will set up the Raspberry Pi pins to allow you to use pin 4 as an input. It can then detect when the PIR module senses motion.
You need the Raspberry Pi to keep checking the pin for any changes. To do this, you need to create a loop in the program which will continue to run until you stop it. This is called a 'while true' loop.
On your Raspberry Pi, open IDLE (Menu>Programming>Python3 (IDLE)).
Create a new file by using the File>New File menu option within IDLE.
Call it security.py
At the top of the file, type this line of code:from gpizero import MotionSensor
This line of code tells Python to use the MotionSensor code library. Rather than having to type lots of code, using tools from the MotionSensor library means you can build your program more quickly.
Save your program.
Call it alarm.py
Add this line underneath. It’s a good idea to leave a blank line to make it easier to read.
from gpizero import MotionSensor
pir = MotionSensor(4)
This tells Python that the motion sensor is plugged into pin number 4 on the Raspberry Pi. From now on just call it “pir”.
Add this line of code to start an infinite loop. You need this because we always want the PIR sensor to be checking for movement.
from gpizero import MotionSensor
pir = MotionSensor(4)
while True:
Add this line of code. It’s important to put spaces at the start of the line so it lines up correctly, as in the image:
from gpizero import MotionSensor
pir = MotionSensor(4)
while True:
if pir.motion_detected:
print("Motion detected!")
This code uses an 'if-statement'. If the PIR sensor detects motion it will display the words 'Motion detected!'
Save your file and test it by pressing 'F5' to run the program.
Every time the PIR detects motion, you should see the words 'Motion detected!' appear in the IDLE window. Press 'Ctrl+F6' when you want to exit.