IOT based Raspberry Pi Home Security System with Email Alert

Published  December 1, 2016   26
S Saddam
Author
IOT based Raspberry Pi Home Security Project with Email Alert

In the world of Internet of Things (IoT) when we have all the technologies to revolutionize our life, it's a great idea to develop a system which can be controlled and monitored from anywhere.  There are many types of good security systems and cameras out there for home security but they are much expensive so today we will build a low cost simple Raspberry Pi based Intruder Alert System, which not only alert you through an email but also sends the picture of Intruder when it detects any.

In this IoT based Project, we will build a Home Security System using PIR Sensor and PI Camera. This system will detect the presence of Intruder and quickly alert the user by sending him a alert mail. This mail will also contain the Picture of the Intruder, captured by Pi camera. Raspberry Pi is used to control the whole system. This system can be installed at the main door of your home or office and you can monitor it from anywhere in the world using your Email over internet. 

 

Components Required:

  • Raspberry Pi
  • Pi Camera
  • PIR Sensor
  • LED
  • Bread Board
  • Resistor (1k)
  • Connecting wires
  • Power supply

You can buy all the components used in this project from here.

Working Explanation:

Working of this Project is very simple. A PIR sensor is used to detect the presence of any person and a Pi Camera is used to capture the images when the presence it detected.

Whenever anyone or intruder comes in range of PIR sensor, PIR Sensor triggers the Pi Camera through Raspberry Pi. Raspberry pi sends commands to Pi camera to click the picture and save it. After it, Raspberry Pi creates a mail and sends it to the defined mail address with recently clicked images. The mail contains a message and picture of intruder as attachment. Here we have used the message “Please find the attachment”, you can change it accordingly in the Code given at the end.

 

Here the pictures are saved in Raspberry Pi with the name which itself contains the time and date of entry. So that we can check the time and date of intruder entry by just looking at the Picture name, check the images below. If you are new with Pi Camera then check our previous tutorial on Visitor Monitoring System with Pi Camera.

Raspberry-Pi-Home-Security-System-pictures-attachment

Raspberry-Pi-Home-Security-System-pictures-on-mail

You can also adjust the detection range or distance of this system using PIR sensor’s potentiometers. Learn more about PIR sensor here to adjust the range also check PIR sensor based Burglar alarm.

 

Circuit Description:

In this Intruder Alert System, we only need to connect Pi Camera module and PIR sensor to Raspberry Pi 3. Pi Camera is connected at the camera slot of the Raspberry Pi and PIR is connected to GPIO pin 18.  A LED is also connected to GPIO pin 17 through a 1k resistor.

Raspberry-Pi-Home-Security-System-circuit-diagram

Pi-Camera

 

Raspberry Pi Configuration and Programming Explanation:

We are using Python language here for the Program. Before coding, user needs to configure Raspberry Pi. You should below two tutorials for Getting Started with Raspberry Pi and Installing & Configuring Raspbian Jessie OS in Pi:

 

After successfully installing Raspbian OS on Raspberry Pi, we need to install Pi camera library files for run this project in Raspberry pi. To do this we need to follow given commands:

$ sudo apt-get install python-picamera
$ sudo apt-get installpython3-picamera

installing-pi-camera-in-raspberry-pi-python

 

After it, user needs to enable Raspberry Pi Camera by using Raspberry Pi Software Configuration Tool (raspi-config):

$ sudo raspi-config

Then select Enable camera and Enable it.

enabling-pi-camera-using-raspberry-pi-config-tool

Then user needs to reboot Raspberry Pi, by issuing sudo reboot, so that new setting can take. Now your Pi camera is ready to use.

 

Now after setting up the Pi Camera, we will install software for sending the mail. Here we are using ssmtp which is an easy and good solution for sending mail using command line or using Python Script. We need to install two Libraries for sending mails using SMTP:

​sudo apt-get install ssmtp
sudo apt-get install mailutils​

ssmtp-installation-in-raspberry-pi-for-mailing

After installing libraries, user needs to open ssmtp.conf file and edit this configuration file as shown in the Picture below and then save the file. To save and exit the file, Press ‘CTRL+x’, then ‘y’ and then press ‘enter’.

sudo nano /etc/ssmtp/ssmtp.conf
root=YourEmailAddress
mailhub=smtp.gmail.com:587
hostname=raspberrypi
AuthUser=YourEmailAddress
AuthPass=YourEmailPassword
FromLineOverride=YES
UseSTARTTLS=YES
UseTLS=YES

ssmtp-configuration-in-raspberry-pi-for-mailing

 

We can also test it by sending a test mail by issuing below command, you shall get the mail on the mentioned email address if everything is working fine:

echo "Hello saddam" | mail -s "Testing..." [email protected]

 

The Python Program of this project plays a very important role to perform all the operations. First of all, we include required libraries for email, initialize variables and define pins for PIR, LED and other components. For sending simple email, smtplib is enough but if you want to send mail in cleaner way with subject line, attachment etc. then you need to use MIME (Multipurpose Internet Mail Extensions).

import RPi.GPIO as gpio
import picamera
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage

 

After it, we have initialized mail and define mail address and messages:

fromaddr = "[email protected]"
toaddr = "[email protected]"
mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Please find the attachment"

 

Then we have created def sendMail(data) function for sending mail:

def sendMail(data):
    mail.attach(MIMEText(body, 'plain'))
    print data
    dat='%s.jpg'%data
    print dat
    attachment = open(dat, 'rb')
    image=MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "your password")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

 

Function def capture_image() is created to capture the image of intruder with time and date.

def capture_image():
    data= time.strftime("%d_%b_%Y|%H:%M:%S")
    camera.start_preview()
    time.sleep(5)
    print data
    camera.capture('%s.jpg'%data)
    camera.stop_preview()
    time.sleep(1)
    sendMail(data)

 

Then we initialized the Picamera with some of its settings:

camera = picamera.PiCamera()
camera.rotation=180
camera.awb_mode= 'auto'
camera.brightness=55

 

And now in last, we have read PIR sensor output and when its goes high Raspberry Pi calls the capture_image() function to capture the image of intruder and send a alert message with the picture of intruder as an attachment. We have used sendmail() insdie capture_image() function for sending the mail.

while 1:
    if gpio.input(pir)==1:
        gpio.output(led, HIGH)
        capture_image()
        while(gpio.input(pir)==1):
            time.sleep(1)
        
    else:
        gpio.output(led, LOW)
        time.sleep(0.01)

 

So this how this Raspberry Pi Security System works, you can also use Ultrasonic sensor or IR sensor to detect the presence of burglar or intruder. Further check the Full Code and demonstration Video below. 

Code

import RPi.GPIO as gpio
import picamera
import time

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage
 
fromaddr = "[email protected]"    # change the email address accordingly
toaddr = "[email protected]"
 
mail = MIMEMultipart()
 
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Please find the attachment"

led=17
pir=18
HIGH=1
LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(led, gpio.OUT)            # initialize GPIO Pin as outputs
gpio.setup(pir, gpio.IN)            # initialize GPIO Pin as input
data=""

def sendMail(data):
    mail.attach(MIMEText(body, 'plain'))
    print data
    dat='%s.jpg'%data
    print dat
    attachment = open(dat, 'rb')
    image=MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "your password")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

def capture_image():
    data= time.strftime("%d_%b_%Y|%H:%M:%S")
    camera.start_preview()
    time.sleep(5)
    print data
    camera.capture('%s.jpg'%data)
    camera.stop_preview()
    time.sleep(1)
    sendMail(data)

gpio.output(led , 0)
camera = picamera.PiCamera()
camera.rotation=180
camera.awb_mode= 'auto'
camera.brightness=55
while 1:
    if gpio.input(pir)==1:
        gpio.output(led, HIGH)
        capture_image()
        while(gpio.input(pir)==1):
            time.sleep(1)
        
    else:
        gpio.output(led, LOW)
        time.sleep(0.01)

Video

Have any question realated to this Article?

Ask Our Community Members

Comments

Submitted by FYI on Thu, 04/06/2017 - 22:16

Permalink

AttributeError: 'module' object has no attribute 'PiCamera' , help me please i'm using python2

Submitted by kartik on Tue, 06/20/2017 - 11:18

Permalink

I AM GETTING THIS ERROR:- smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted.

Please note that I have already allowed gmail to allow less security apps

Submitted by Amit on Mon, 09/11/2017 - 07:58

Permalink

Fabulous instructions! Thanks a heap!
The sensor always captures and sends images (false positives) even if there is no movement detected. Can you help me figure out this problem please?

Submitted by Vaibhav on Sat, 09/16/2017 - 13:07

Permalink

Dear sir it just capturing only one image after i runthe program
After that its not clicking next image even though i keep movement infront of sensor
What that sleep.time() matters there

Submitted by Shashidhar on Sun, 09/17/2017 - 12:06

Permalink

Can you tell the references,scope and problem definition of this project... because I have taken this project as my 8th semester major project...

Submitted by sagaor saha on Fri, 10/06/2017 - 20:38

Permalink

"process exited with a non-zero status"
this line is being shown. help me please

Submitted by amer on Tue, 03/06/2018 - 21:41

Permalink

hi..
i want asimple program to connect motion sensor and wep camera and active email notification

Submitted by Veeru on Mon, 03/12/2018 - 11:29

Permalink

Getting error in testing the mail address

Submitted by Ravi meena on Wed, 03/21/2018 - 13:31

Permalink

how to use this code

where we have to run the code

Submitted by aman on Mon, 04/23/2018 - 20:15

Permalink

I am getting a bad credential error when i execute the whole code, but i am able to send the test
email .
i used jupyter notebook to run the code

Submitted by John on Thu, 05/31/2018 - 03:31

Permalink

Thanks for the code. It seems to be working great! I want to use it for home security system, but is there a way to send more than 2 images, and / or a video image? Thanks!

Submitted by John on Thu, 05/31/2018 - 14:28

Permalink

Hi, I tried modifying the code to get email alerts to more than one address.
Separating addresses with a comma only sends the alert to the first email address: toaddr="[email protected], [email protected]"
I also tried replacing toaddr with recipients:
recipients:=[email protected], [email protected]" (and replacing all toaddr in the script with recipients)
This sends the alert only to the first email, but with the second email included in the same email, so I can manually forward to the second email, but I would prefer automatic sending to both addresses.
Any way to modify the code to send to more than one email address? Thank you

Submitted by deepak on Wed, 06/13/2018 - 15:28

Permalink

sudo apt-get install mailutils

E: Unable to locate package mailutils​

plz guide me to solve this problem

pi@raspberrypi:~ $ sudo apt-get install ssmtp
Reading package lists... Done
Building dependency tree
Reading state information... Done
ssmtp is already the newest version (2.64-8).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
pi@raspberrypi:~ $ sudo apt-get install mailutils
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
guile-2.0-libs libgc1c2 libgsasl7 libkyotocabinet16v5 libmailutils5
libmariadbclient18 libntlm0 mailutils-common mysql-common
Suggested packages:
mailutils-mh mailutils-doc
The following NEW packages will be installed:
guile-2.0-libs libgc1c2 libgsasl7 libkyotocabinet16v5 libmailutils5
libmariadbclient18 libntlm0 mailutils mailutils-common mysql-common
0 upgraded, 10 newly installed, 0 to remove and 0 not upgraded.
Need to get 710 kB/5,538 kB of archives.
After this operation, 21.6 MB of additional disk space will be used.
Do you want to continue? [Y/n]