I had an old Raspberry Pi B+ just gathering dust so I decided to build a small home security device.
You'll need four things for this project a Raspberry pi, a PIR sensor, Jumper wires(female to female) and a gmail account.
Connecting the Raspberry Pi with the PIR sensor
Step 1: Connecting the RIP sensor to your Raspberry Pi.
Below is the RIP sensor pins to GPIO
VCC to 5V
the OUT to GPIO pin4
the GND to GND
Step 2: Install the OS.
NOOBS is available for download on the Raspberry Pi website:raspberrypi.org/downloads
To set up a blank SD card with NOOBS:
Format an SD card which is 8GB or larger as FAT. See the instructions given below.
Download and extract the files from the NOOBS zip file.
Copy the extracted files onto the SD card that you just formatted
Step 4: Create the Python script
Open up the terminal and create a new file called pirsensor.py by typing:
>> nano pirsensor.pyCopy or type the code into the file.
import RPi.GPIO as GPIO import time sensor = 4 GPIO.setmode(GPIO.BCM) GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN) previous_state = False current_state = False while True: time.sleep(0.1) previous_state = current_state current_state = GPIO.input(sensor) if current_state != previous_state: new_state = "HIGH" if current_state else "LOW" print("GPIO pin %s is %s" % (sensor, new_state)) import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("from_email_address", "from_email_password") msg = "INTRUDER!" server.sendmail("from_email_address", "to_email_address", msg) server.quit()
Edit the from/to email and edit you email password.
Step 5: Test the code
Run the code by typing the following into the terminal:
>> sudo python3 pirsensor.py
When motion has been detected GPIO pin 4 will read HIGH(this will be printed in the terminal) but when there is no motion detected GPIO pin 4 reads LOW(also printed in the terminal). When pin 4 reads high you will get an email saying "INTRUDER!".
Note: You will need to allow apps to access your gmail account, you can do that here.
Set the Python script to auto run on start up
I'm using Linux crontab to auto run the Python script when I turn on the Raspberry Pi.
This allows me to just plug in the pi and leave my house.
Open the terminal and type:
In the terminal editor, type in this script
#!/bin/sh # launcher.sh # navigate to home directory, then to this directory, # then execute python script, then back home
cd / cd home/pi/ sudo python3 pirsensor.py cd /
Press Ctl-X and save.
We need to make the launcher script an executable, which we do with this command
chmod 755 launcher.sh
Now test it, by typing in:
This should run your Python code.
Setting the code to run...Open the terminal and type
sudo crontab -e
This will brings up a crontab window.
Now on the last line enter the below text:
@reboot sh /home/pi/bbt/launcher.sh
Now unplug the power cable or reboot your Rapberry PI.