Home Security Systems are a need of the modern day houses. It is possible to design a simple home security solution by using Raspberry Pi and utilizing the power of Internet of Things. The home security system designed in this project is a simple and easily installable device built using Raspberry Pi 3, Web Cam and PIR Motion Sensor. The Raspberry Pi 3 Model B comes equipped with on-board Bluetooth (BLE) and Wi-Fi (BCM43438 Wireless LAN), so, it can be easily connected with a Wi-Fi Router to access a cloud service.
The device designed in this project can be installed at the main entrance of a house. It detects motion of any visitor with the help of PIR sensor and starts capturing the images with the help of a USB web cam. The images are temporarily stored on the Raspberry Pi and pushed to the Google Cloud from where they are sent as email alert to the house owner. So, the user gets the images of any visitor immediately on email which he can check from his smart phone. The Raspberry Pi connects with the Google Cloud over TCP-IP stack. The Raspberry Pi 3 is one of the IoT boards which comes equipped with on-board TCP/IP stack, so, it can be readily connected to an IoT network. The Pi uses OpenCV library to capture images from the Web Cam and send them over registered Email address of the user.
The home security system designed in this project, though being simple, is a powerful application. The user can keep surveillance of his house from anywhere, any time and always by just installing this small device at the main entrance. Many such devices can also be installed to further add security layers. The entrance of any intruder can be detected and alerted by the Email on the smart phone, then the user is free to take appropriate action like calling police, informing law enforcement etc.
Fig. 1: Prototype of Raspberry Pi 3 based IoT Home Security System
Components Required –
Fig. 2: List of Components required for Raspberry Pi 3 based IoT Home Security System
Block Diagram –
Fig. 3: Block Diagram of Raspberry Pi 3 based IoT Home Security System
Circuit Connections –
The IoT device designed in this project is based on Raspberry Pi 3 which is a single board computer with bluetooth and wireless LAN connectivity. The Pi is interfaced with PIR sensor, USB web camera and a power supply to form the entire system. The device can be installed at any place where required. The PIR sensor is connected to the GPIO pins of the Raspberry Pi. An LCD monitor can be used for setting the Raspberry Web Server. The images captured from the USB Web Camera can be saved with time and date information on a SD card.
Fig. 4: Image showing circuit connections of Raspberry Pi 3 based IoT Home Security System
The IoT device designed in this project has the following components connected with the below mentioned circuit connections –
Raspberry Pi 3 – Raspberry Pi 3 is the third generation Raspberry Pi. It is a miniature marvel, packing considerable computing power into a footprint no larger than a credit card. The processor at the heart of the Raspberry Pi system is a Broadcom BCM2837 system-on-chip (SoC) which houses a 1.2 GHz Quad Core ARM Cortex-A53 processor. The vast majority of the system’s components, including its central and graphics processing units along with the audio and communications hardware, are built onto that single component along with 1 GB LPDDR2 memory chip at the centre of the board. It is not just this SoC design that makes the BCM2837 different to the processor found in a typical desktop or laptop, however, it also uses a different instruction set architecture (ISA), known as ARM.
The Pi comes equipped with on-board 10/100 BaseT Ethernet Socket, HDMI and Composite RCA port for video, 3.5 mm audio output jack, 15-pin MIPI Camera Serial Interface (CSI-2), Display Serial Interface, Bluetooth 4.1, 802.11 b/g/n Wireless LAN, Micro SDIO for Micro SD Card, 4 USB 2.0 Connectors, 40 pin header containing 27 GPIO pins and Micro USB socket for power supply.
The Raspberry Pi is a single board computer and is designed to run an operating system called GNU/Linux Raspbian. Hereafter referred to simply as Linux. Unlike Windows or OS X, Linux is open source, so it is possible to download the source code for the entire operating system and make whatever changes desired. The Raspberry Pi 3 can also run Windows 10 IoT and many other embedded operating systems most of which are Linux derivatives. The operating system should be loaded in a MicroSD card and boot from it. With powerful computing resources, large number of multimedia interfaces and GPIO pins, Raspberry Pi 3 is a suitable choice to run a software oriented complex IoT or Embedded project that requires sufficient computing power as well as large scale sensor connectivity. With on-board Bluetooth and Wi-Fi, this 3rd generation Pi can be easily deployed in an IoT network. The key specifications of the Raspberry Pi 3 are summarized in the following table –
Fig. 5: Table listing technical specifications of Raspberry Pi 3
The 40-pin header on Raspberry Pi 3 has the following pin configuration –
Fig. 6: Table listing pin configuration of Raspberry Pi 3
Fig. 7: Table listing pin configuration of Raspberry Pi 3
In this project, the USB Web Cam is connected to one of the four USB 2.0 connectors and PIR sensor is interfaced to GPIO04 (Pin 7) at the header of the Pi 3.
PIR Sensor – The PIR (Passive Infra-Red) Sensor is a Pyroelectric device that detects motion by measuring changes in the infrared levels emitted by surrounding objects. By incorporating a Fresnel lens and motion detection circuit, the module provides high sensitivity and low noise. The module provides an optimized circuit that can detect motion up to 6 meters away. There are two slots on the sensor, each made up of a special IR sensitive material. In the absence of anybody, the two slots receive the same amount of IR radiation. When a person passes by the sensor, it is intercepted by one half of the slots causing a positive potential difference across the slots. When the person leaves by the sensor, it is intercepted by another half of the slots causing a negative potential difference across the slots. This positive and negative differential generates a pulse thus detecting motion.
The sensor module has on-board 3.3 V voltage regulator, protection diode, sensitivity adjustment and delay time adjust. There are three terminals on the module – ground, VCC and Digital Out. A voltage of 5V to 12 V can be supplied at the VCC pin, though 5V is the recommended power supply. When the module detects motion, the output at the Digital Out pin goes HIGH. This is a standard 5V active high signal. The Digital Out pin of the sensor is connected to GPIO pins of Raspberry Pi directly to monitor signal. It is connected to GPIO 4th pin of Raspberry pi 3. The VCC pin of the module is connected to one of the 5V DC Power pin of the Pi 3 and ground pin of the module is connected to one of the ground pins of the Pi.
USB Web Camera – A Web Camera module is interfaced with the Raspberry Pi through one of USB ports in Raspberry pi 3. The OpenCV library is used to provide the functionality to work with this standard web cam.
Power Supply – The power source is connected to the Raspberry Pi. The Pi should be powered by a 5V adapter with 2A current output. The adaptor can be connected at Micro USB socket.
How the circuit works –
The IoT device built on Raspberry Pi 3 in this project has a simple and straight forward operation. The device detects motion by the PIR sensor and as it detects motion, it starts capturing images. The images are stored on the MicroSD card and sent on the registered email of the user. All of this is managed by a python script running over the Raspbian Operating System. Before running the python script, it is essential to install operating system on the Pi 3 and install the required libraries i.e. OpenCV on the operating system. While installing the operating system, installing the libraries and the python script, the Raspberry Pi should be connected to a display monitor using HDMI cable.
For installing the Raspbian Operating System on MicroSD card, first download the latest image of Raspbian OS from Raspberry Pi website from the following link –
Copy the image of the latest Raspbian OS in the MicroSD card. If the MicroSD card used is 32 GB or below, it must be formatted to FAT32 (file system) before copying the image or if the MicroSD card is more than 32 GB, it should be formatted to exFAT before copying the image. Extract the OS Zip and copy it to the MicroSD card. The image can be written to the card by connecting the card to a laptop or PC using a MicroSD card reader. After copying the extracted image, insert the card in the MicroSD slot as shown below –
Fig. 8: Typical Image of Raspberry Pi 3 MicroSD Card Slot
Connect the Raspberry Pi with a display monitor using HDMI Cable, a keyboard and a mouse. Power on the board by connecting to a power adaptor. The red LED on the board will start blinking and the OS will start booting from the MicroSD card. The boot process will display on the monitor and once the boot is complete, green LED will light up on the Raspberry Pi. After successfully installing Raspbian OS on Raspberry Pi, it is recommended to perform software update. It can be done by running the following Linux commands in the Linux Terminal –
$ sudo apt-get update
$ sudo apt-get upgrade
Now, it’s time to install OpenCV library. There are lots of methods available to install OpenCV. The simplest method to install the OpenCV on Linux is given in the OpenCV website. Check out the following link –
Open the Linux terminal on the Raspbian and execute the following commands –
1. First install the compiler by running the following command –
$ sudo apt-get install build-essential
2. Install the required packages by running the following command –
$ sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
3. Next install optional packages by running the following command –
$ sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev
4. Install the OpenCV to any directory by running the following commands –
$ cd <Directory_name>
$ git clone https//:github.com/opencv/opencv.git
5. Next, create a temporary directory (<cmake_directory>) where the generated make files, project files, object files and output binaries should be saved. This can be done by running the following commands –
$ cd opencv
$ mkdir build
$ cd build
$ cmake –D CMAKE_BUILD_TYPE=RELEASE –D CMAKE_INSTALL_PREFIX=/usr/local ..
6. Move to the (<cmake_directory>) that is created in above step and install the OpenCV by running the following commands –
$ sudo make install
After installing the Raspbian and OpenCV, it’s time to write and run the python script on Raspbian. A python script can be written on Raspbian using a text editor like Leafpad or GNU Nano. The python script can also be written using the default python IDE like Python 2 IDLE or Python 3 IDLE. Open the Python 3 IDLE by navigating through Menu -> Programming -> Python 3 IDLE. A window called Python 3.4.2 Shell will open up. Write the python script and save it to a directory.
The python script written for this project should run at the startup as the Pi 3 is powered on. The script runs an infinite loop so it never ends. There are some methods by which the Raspberry Pi can be configured to run a python script on start up. Any of the following methods can be used –
1) Editing rc.local –
The commands can be added to the file /etc/rc.local to run a program or command when the raspberry Pi boots up. This is especially useful if the Pi has to plug in to power headless, and have it run a program without configuration or a manual start. The file should be edited with root by running the following commands in the Linux Terminal –
sudo nano /etc/rc.local
Now add commands to execute the python script using complete file path and add an ampersand at the end of the command so that the script runs in a separate process and booting could continue. The following command should be added where the python script is saved as securitysystem.py –
sudo python /home/pi/securitysystem.py &
The command should be added just before the line exit 0 in the rc.local file.
2) Editing .bashrc –
The .bashrc is a hidden file in the home folder that contains user configuration options. Open the .bshrc file by running the following commands in the Linux terminal –
sudo nano /home/pi/.bashrc
Add the following lines after the last line in the file –
echo Running at boot
sudo python /home/pi/securitysystem.py
3) Adding script to init.d directory –
The init.d directory contains the scripts which are started during the boot process (in addition, all programs here are executed when Pi is shutdown or rebooted). Add the script to be run at startup to the init.d directory using the following commands –
sudo cp /home/pi/securitysystem.py /etc/init.d/
Move to the init directory and open the python script by running the following commands –
sudo nano securitysystem.py
Add the following lines to the python script to make it a Linux Standard Base (LSB) –
### BEGIN INIT INFO
# Provides: sample.py
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start daemon at boot time
# Description: Enable service provided by daemon.
### END INIT INFO
Make the python script in the init directory executable by changing its permission by running the following command –
sudo chmod +x securitysystem.py
Then run the following command –
sudo update-rc.d securitysystem.py defaults
Next reboot the Pi by running the following command –
Any of the above methods can be used to make the python script run on startup. Now the Pi 3 can be disconnected with the display monitor, keyboard and mouse. The Web camera and the PIR sensor should be connected to complete the device circuit. Now on startup, the python script runs along with the boot process.
The E–mail System is implemented on the Raspberry pi development board in Linux environment, which supports SMTP (Simple Mail Transfer Protocol), TCP/IP and HTTP. The web server Flash File System supports dynamically generated files that can include output data from hardware resources. This type of file is called an embedded server page (ESP).
When the PIR sensor detects motion at the entrance, its digital output is set to HIGH. In the python script when the GPIO 4 goes high, the webcam connected to the raspberry pi takes the snap of the entrance and send the image attachments to the mail.
Programming Guide –
The python script that is written and made to run on the startup manages the entire functionality of the project. At beginning of the code, import statements are used to import standard libraries like RPi.GPIO, time, cv2 and numpy. These libraries are used for accessing GPIO pins, extract the system time, and use OpenCV module in order to capture the images. The variables are declared for GPIO pin number for PIR sensor and to provide the email ID that is to be used to send and receive the alert mail. The GPIO.setmode(GPIO.BCM) is used to set the board to Broadcom mode.
Fig. 9: Screenshot of Initialization Code in Python Script for Raspberry Pi based Smart IoT Home Security System
On script execution, it enters into an infinite loop where the PIR sensor continuously monitors and once the change in the input is detected, the camera switches on and captures photo. The image that is captured is saved with date time as picname using the datetime module and the image is send through mail with subject and body.
Fig. 10: Screenshot of Loop Function in Python Script for Raspberry Pi based Smart IoT Home Security System
Check out the complete python script for better understanding.
You may also like:
Project Source Code
###//Program to import RPi.GPIO as GPIO import time import numpy as np import cv2 from datetime import datetime import os import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders gmail_user = "FROM MAIL [email protected]" #Sender email address gmail_pwd = "FROM MAIL PASSWORD" #Sender email password to = "TO MAIL [email protected]" #Receiver email address subject = "Security Alert" text = "There is some activity in your home. See the attached picture." sensor = 4 GPIO.setmode(GPIO.BCM) GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN) previous_state = False current_state = False while True: 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)) if current_state: cap = cv2.VideoCapture(0) ret, frame = cap.read() cap = cv2.VideoCapture(0) print "Saving Photo" picname = datetime.now().strftime("%y-%m-%d-%H-%M") picname = picname+'.jpg' cv2.imwrite(picname, frame) print "Sending email" attach = picname msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() print "Email Sent" os.remove(picname)