Home security systems are a necessity for modern homes. It is possible to design a simple home security solution using Raspberry Pi and utilizing the power of the Internet of Things. The home security system designed in this project is a simple and easy-to-install device, built with Raspberry Pi 3, Web Cam and PIR motion sensor. The Raspberry Pi 3 Model B comes equipped with built-in Bluetooth (BLE) and Wi-Fi (BCM43438 Wireless LAN), so it can be easily connected to 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 the movement of any visitor with the help of PIR sensor and starts capturing images with the help of a USB web cam. The images are temporarily stored on the Raspberry Pi and sent to Google Cloud, from where they are sent as an email alert to the home owner. Thus, the user receives the images of any visitor immediately by email, which they can consult on their smartphone. The Raspberry Pi connects to Google Cloud via the TCP-IP stack. Raspberry Pi 3 is one of the IoT boards that comes equipped with built-in TCP/IP stack, hence it can be easily connected to an IoT network. The Pi uses the OpenCV library to capture images from the Web Cam and send them via the user's registered email address.
The home security system designed in this project, although simple, is a powerful application. The user can monitor their home from anywhere, anytime and always, simply by installing this small device at the main entrance. Many of these devices can also be installed to add even more layers of security. The entry of any intruder can be detected and alerted via email on the smartphone, so the user is free to take appropriate measures, such as calling the police, informing the authorities, etc.
Figure 1: IoT home security system prototype based on Raspberry Pi 3
Required components –
Figure 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 interfaces with a PIR sensor, USB webcam and power supply to form the entire system. The device can be installed anywhere it is needed. The PIR sensor is connected to the GPIO pins of the Raspberry Pi. An LCD monitor can be used to configure the Raspberry Web Server. Images captured from the USB Web Camera can be saved with time and date information to an SD card.
Figure 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 to the circuit connections mentioned below –
Raspberry Pi 3 – Raspberry Pi 3 is the third generation Raspberry Pi. It's a miniature marvel, packing considerable computing power into a space no bigger than a credit card. The Raspberry Pi system's central processor is a Broadcom BCM2837 system-on-chip (SoC) that 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 into this single component, along with the 1GB LPDDR2 memory chip at the center of the board. It's not just this SoC design that makes the BCM2837 different from 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 an integrated 10/100 BaseT Ethernet socket, composite HDMI and RCA port for video, 3.5mm 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 to Micro SD card, 4 USB 2.0 connectors, 40-pin connector containing 27 GPIO pins and Micro USB socket for power supply.
The Raspberry Pi is a single-board computer designed to run an operating system called GNU/Linux Raspbian. Hereinafter referred to simply as Linux. Unlike Windows or OS X, Linux is open source, so you can download the source code for the entire operating system and make any changes you want. The Raspberry Pi 3 can also run Windows 10 IoT and many other embedded operating systems, many of which are derived from Linux. The operating system must be loaded onto a MicroSD card and booted from it. With powerful computing capabilities, large number of multimedia interfaces and GPIO pins, the Raspberry Pi 3 is a suitable choice for running a complex software-driven IoT or Embedded project that requires sufficient computing power as well as large-scale sensor connectivity . With built-in Bluetooth and Wi-Fi, this 3rd generation Pi can be easily deployed in an IoT network. The main specifications of the Raspberry Pi 3 are summarized in the following table –
Figure 5: Table listing technical specifications of the Raspberry Pi 3
The 40-pin header on Raspberry Pi 3 has the following pin configuration –
Fig. 6: Table listing the Raspberry Pi 3 pin configuration
Fig. 7: Table listing the Raspberry Pi 3 pin configuration
In this project, the USB Web Cam is connected to one of the four USB 2.0 connectors and the PIR sensor is connected to GPIO04 (pin 7) on the Pi 3 header.
PIR Sensor – The PIR (Passive Infrared) Sensor is a pyroelectric device that detects movement by measuring changes in the levels of infrared emitted by surrounding objects. By incorporating a Fresnel lens and motion detection circuitry, the module offers high sensitivity and low noise. The module provides an optimized circuit that can detect movement up to 6 meters away. There are two slots on the sensor, each made of a special infrared-sensitive material. In the absence of someone, both slots receive the same amount of infrared radiation. When a person passes through the sensor, they are intercepted by half of the slots, causing a positive potential difference between the slots. When the person exits the sensor, they are intercepted by another half of the slits causing a negative potential difference between the slits. This positive and negative differential generates a pulse detecting movement.
The sensor module has an integrated 3.3V voltage regulator, protection diode, sensitivity adjustment and delay time adjustment. There are three terminals on the module – ground, VCC and digital output. A voltage of 5V to 12V can be supplied at the VCC pin, although 5V is the recommended power supply. When the module detects movement, the output on the Digital Out pin goes HIGH. This is a standard 5V active high signal. The sensor's Digital Out pin is connected to the Raspberry Pi's GPIO pins directly to monitor the signal. It is connected to the 4th GPIO pin of the Raspberry pi 3. The VCC pin of the module is connected to one of the 5V DC power pins of the Pi 3 and the ground pin of the module is connected to one of the ground pins of the Pi.
USB Web Camera – A web camera module interfaces with the Raspberry Pi through one of the Raspberry pi 3's USB ports. The OpenCV library is used to provide the functionality to work with this standard webcam.
Power supply – The power supply is connected to the Raspberry Pi. The Pi must be powered by a 5V adapter with 2A current output. The adapter can be plugged into the Micro USB socket.
How the circuit works –
The IoT device built on Raspberry Pi 3 in this project has simple and straightforward operation. The device detects movement through the PIR sensor and as it detects movement, it starts capturing images. The images are stored on the MicroSD card and sent to the user's registered email. All of this is managed by a python script running on the Raspbian operating system. Before running the python script, it is essential to install the operating system on the Pi 3 and install the necessary libraries i.e. OpenCV on the operating system. When installing the operating system, installing the libraries and python script, the Raspberry Pi must be connected to a monitor using an HDMI cable.
To install Raspbian OS on MicroSD card, first download the latest Raspbian OS image from the Raspberry Pi website at the following link –
Raspbian operating system
Copy the latest Raspbian operating system image to the MicroSD card. If the MicroSD card used is 32 GB or less, it must be formatted to FAT32 (file system) before copying the image, or if the MicroSD card is more than 32 GB, it must be formatted to exFAT before copying the image. Extract the operating system Zip and copy it to the MicroSD card. The image can be written to the card by connecting it to a laptop or PC using a MicroSD card reader. After copying the extracted image, insert the card into the MicroSD slot as shown below –
Figure 8: Typical image of the Raspberry Pi 3 MicroSD card slot
Connect the Raspberry Pi to a monitor using an HDMI cable, a keyboard, and a mouse. Power the card by connecting it to a power adapter. The red LED on the board will begin blinking and the operating system will begin booting from the MicroSD card. The boot process will be displayed on the monitor and once the boot is complete, the green LED will light up on the Raspberry Pi. After successfully installing Raspbian OS on Raspberry Pi, it is recommended to perform a software update. This can be done by running the following Linux commands in the Linux Terminal –
$ sudo apt-get update
$ sudo apt-get update
Now it's time to install the OpenCV library. There are several methods available to install OpenCV. The simplest method to install OpenCV on Linux is provided on the OpenCV website. Check out the following link –
OpenCV installation on Linux
Open the Linux terminal on Raspbian and run 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. Then install the 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 OpenCV in any directory by running the following commands –
$cd
$ git clone https://:github.com/opencv/opencv.git
5. Then create a temporary 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 compilation
$cd compilation
$ cmake –D CMAKE_BUILD_TYPE=RELEASE –D CMAKE_INSTALL_PREFIX=/usr/local ..
6. Go to ( ) created in the above step and install OpenCV by running the following commands –
$do
$ sudo make install
After installing Raspbian and OpenCV, it's time to write and run the python script on Raspbian. A python script can be written in Raspbian using a text editor like Leafpad or GNU Nano. Python script can also be written using standard python IDE such as Python 2 IDLE or Python 3 IDLE. Open Python 3 IDLE by navigating through Menu -> Programming -> Python 3 IDLE. A window called Python 3.4.2 Shell will open. Write the python script and save it in a directory.
The python script written for this project must be run at startup when the Pi 3 is turned on. The script runs an infinite loop so it never ends. There are a few methods by which the Raspberry Pi can be configured to run a python script at startup. Any of the following methods can be used –
1) Editing rc.local –
Commands can be added to the /etc/rc.local file to run a program or command when the Raspberry Pi boots. This is especially useful if the Pi needs to be plugged into headless power and run a program without manual configuration or initialization. The file must be edited with root by running the following commands in the Linux Terminal –
sudo nano /etc/rc.local
Now add commands to run the python script using the full file path and add an ampersand at the end of the command so that the script runs in a separate process and initialization can continue. The following command must be added where the python script is saved as securitysystem.py –
sudo python /home/pi/securitysystem.py &
output 0
The command must be added just before the output 0 line 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 of the file –
echo Running at startup
sudo python /home/pi/securitysystem.py
3) Adding script to init.d directory –
The init.d directory contains the scripts that are launched during the boot process (additionally, all programs here run when the Pi is turned off 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/
Go to the init directory and open the python script by running the following commands –
cd /etc/init.d
sudo nano securitysystem.py
Add the following lines to the python script to make it a Linux Standard Base (LSB) –
# /etc/init.d/sample.py
### STARTING INFORMATION
# Provide: sample.py
# Mandatory start: $remote_fs $syslog
# Mandatory stop: $remote_fs $syslog
# Default start: 2 3 4 5
# Default stop: 0 1 6
# Short description: Start daemon at boot time
# Description: Enables the service provided by the daemon.
### END START INFORMATION
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 –
defaults sudo update-rc.d securitysystem.py
Then restart the Pi by running the following command –
sudo restart
Any of the above methods can be used to run the python script on startup. Now the Pi 3 can be disconnected from the monitor, keyboard and mouse. The webcam and PIR sensor must be connected to complete the device circuit. Now on startup, the python script runs along with the initialization process.
The email system is implemented on the Raspberry pi development board in a Linux environment, which supports SMTP (Simple Mail Transfer Protocol), TCP/IP and HTTP. The web server's 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 input, 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 input and sends the image attachments to the email.
Programming guide –
The python script written and executed at startup manages all the functionality of the project. At the beginning of the code, import statements are used to import standard libraries such as RPi.GPIO, time, cv2, and numpy. These libraries are used to access the GPIO pins, extract the system time and use the OpenCV module to capture the images. Variables are declared for the GPIO PIN number of the PIR sensor and to provide the email ID that will be used to send and receive the alert email. GPIO.setmode (GPIO.BCM) is used to set the card to Broadcom mode.
Fig. 9: Screenshot of startup code in Python script for Raspberry Pi based Smart IoT home security system
While executing the script, it goes into an infinite loop where the PIR sensor continuously monitors and once the change in input is detected, the camera turns on and captures the photo. The captured image is saved with date and time as picname using the datetime module and the image is sent by 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.
Project source code
###
//Program to import RPi.GPIO as GPIO import time import numpy as np import cv2 from datetime import datetime import them 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" #Send 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 whileTrue: 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 Send" os.remove(picname)###
Circuit diagrams
Circuit-Diagram-Raspberry-Pi-3-based-IoT-Home-Security-System |