Internet of Things (IoT) Lab Manual123
Internet of Things (IoT) Lab Manual123
Raspberry Pi is popularly used for real time Image/Video Processing, IoT based
applications and Robotics applications.
Raspberry Pi is slower than laptop or desktop but is still a computer which can provide
all the expected features or abilities, at a low power consumption.
Raspberry Pi Foundation officially provides Debian based Raspbian OS. Also, they
provide NOOBS OS for Raspberry Pi. We can install several Third-Party versions of OS
like Ubuntu, Archlinux, RISC OS, Windows 10 IOT Core, etc.
Raspbian OS is official Operating System available for free to use. This OS is efficiently
optimized to use with Raspberry Pi. Raspbian have GUI which includes tools for
Browsing, Python programming, office, games, etc.
Raspberry Pi is more than computer as it provides access to the on-chip hardware i.e.
GPIOs for developing an application. By accessing GPIO, we can connect devices like
LED, motors, sensors, etc and can control them too.
It has ARM based Broadcom Processor SoC along with on-chip GPU (Graphics
Processing Unit).
The CPU speed of Raspberry Pi varies from 700 MHz to 1.2 GHz. Also, it has on-board
SDRAM that ranges from 256 MB to 1 GB.
ENROLLMENT NO: 1
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Raspberry Pi also provides on-chip SPI, I2C, I2S and UART modules.
1. Raspberry Pi 1 Model A
2. Raspberry Pi 1 Model A+
3. Raspberry Pi 1 Model B
4. Raspberry Pi 1 Model B+
5. Raspberry Pi 2 Model B
6. Raspberry Pi 3 Model B
7. Raspberry Pi Zero
Out of the above versions of Raspberry Pi, more prominently use Raspberry Pi and their
features are as follows:
ENROLLMENT NO: 2
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Raspberry Pi Zero
ENROLLMENT NO: 3
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Raspberry Pi Board
ENROLLMENT NO: 4
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 5
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
4. Composite Video and Audio Output: The composite Video and Audio output port
carries video along with audio signal to the Audio/Video systems.
5. Power LED: It is a RED colored LED which is used for Power indication. This LED
will turn ON when Power is connected to the Raspberry Pi. It is connected to 5V
directly and will start blinking whenever the supply voltage drops below 4.63V.
6. ACT PWR: ACT PWR is Green LED which shows the SD card activity.
ENROLLMENT NO: 6
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
HDMI Cable
ENROLLMENT NO: 7
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
● But, if we have a computer monitor (VGA Display), then we need an HDMI to VGA
converter along with a VGA cable for connecting Raspberry Pi with monitors.
HDMI to VGA converter and VGA cable is shown below.
ENROLLMENT NO: 8
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
VGA Cable
Now, connect the Raspberry Pi to the Display/monitor and Power-On Raspberry Pi. We
will get a Black command window asking for Login and Password as shown below
ENROLLMENT NO: 9
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 10
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
raspberrypi Login: pi
Password: raspberry
● This is the default user name and password. You can change the password after
the first login.
startx
ENROLLMENT NO: 11
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
● As we can see, the Raspbian OS has installed Python 2 & 3. It also has different
programming IDE like Geany, BlueJ Java IDE, etc. As raspberry pi 3 has On-chip
WiFi, we can connect it to the network and will get access over Internet.
● We can also change password of “Pi” user.
● To change password, click on preferences and then select Raspberry Pi
Configuration which will provide a pop-up window.
ENROLLMENT NO: 12
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 13
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 14
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Introduction
After downloading Raspbian on SD card, open SD card in laptop and then open directory
given below:
ctrl_interface=DIR=/var/run/wpa_supplicant Group=netdev
update_config=1
country=US
network {
ssid=”Enter your SSID”
psk=”Enter your password”
key_mgmt=WPA-PSK
}
ENROLLMENT NO: 15
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now, open following directory and add highlighted line shown in below image,
Also for remote login into raspberry using SSH, we need to enable SSH on Raspberry Pi.
ENROLLMENT NO: 16
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
To enable SSH, just add a file named ssh with no extension onto the boot partition of SD
Now, eject the SD card and insert it into Raspberry Pi Board and power-on Raspberry Pi.
Raspberry Pi will now connect to WiFi network automatically after booting. Now, we can
find the IP address of Raspberry Pi using Advance IP scanner. Advance IP scanner
scans the network and provides list of connected device. In that we will get IP address
of Raspberry Pi. to know about how to use Advance IP scanner, you can refer Access
Raspberry Pi Home Screen on Laptop Display using LAN
After getting IP address of Raspberry Pi, use Putty (SSH) for logging into the raspberry
Pi given in below demo,
Now, we can access Raspberry Pi CLI (Command Line Interface). If we have to access
Raspberry Pi GUI then we can access it using VNC viewer. Before using VNC viewer, we
need to enable it using command.
To access Raspberry Pi’s Graphical user interface, we can use VNC viewer which allows
us to control the Raspberry Pi home remotely using Mobile, Laptop, etc. With VNC
server, we can see Raspberry Pi home on our computer or mobile.
To enable VNC viewer on Raspberry Pi use CLI (command line interface) and following
few steps given below,
sudo raspi-config
ENROLLMENT NO: 17
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 18
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now, we can connect to Raspberry Pi using VNC Server. For login to Raspberry Pi using
VNC, Download and Install VNC viewer application on laptop.
After installing VNC viewer application, the application window will appear as shown
below,
ENROLLMENT NO: 19
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now, select File option and in that select new connection as shown below,
ENROLLMENT NO: 20
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 21
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Enter IP of your Raspberry Pi which was found by Advance IP scanner and provide any
name as shown below,
ENROLLMENT NO: 22
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 23
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 24
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
We can see the CLI (Command Line Interface) of raspberry Pi. To access Raspberry Pi
in GUI mode, enter following command
startx
and we will get the GUI home screen of Raspberry Pi as shown below.
ENROLLMENT NO: 25
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
WiringPi is a library written in C used to access GPIO pins on Raspberry for BCM2835
(Broadcom Processor) SoC (System on Chip). There are various libraries are available to
access GPIO in C like bcm 2835, sysfs, pigpio, etc. Here, we are using WiringPi library for
Raspberry Pi GPIO access.
To use wiringPi, first we should install it on Raspberry Pi. This installation can be done in
two ways which is as follows,
● Make sure our Raspbian is updated. So, first check for any update and upgrade
on Raspberry Pi.
● Now, we can use git to download WiringPi library. For that we should install git on
Raspberry Pi if already not installed.
● Now, create directory for WiringPi and build it. Also, fetch the updated version
from git.
ENROLLMENT NO: 26
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
cd wiringPi
git pull origin
./build
We can install WiringPi library in other way also. To install WiringPi library on Raspberry
Pi, first we should download it. We can download WiringPi Library here.
On above link, there are more files to download. Just download file which is at the top, is
the latest updated file. By clicking on snapshot, we can download it.
Now follow the steps(commands) given below to install the above downloaded library,
cd
tar xfz downloaded_filename.tar.gz
cd downloaded_filename
./build
gpio -v
ENROLLMENT NO: 27
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
The above screenshot tells that the WiringPi library is installed successfully.
Now, we can access GPIO using WiringPi library. But, the pin numbering used in Wiring
Pi library is different than GPIO numbering (BCM) and Physical numbering(BOARD).
To get information about pin numbering on our respective Raspberry Pi version, we can
use following command:
gpio readall
ENROLLMENT NO: 28
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
The above screenshot shows pin numbering as per WiringPi, BCM (GPIO numbering)
and Physical numbering(Board).
Here, we will access GPIO on Raspberry Pi using WiringPi library to blink LED.
Interfacing Diagram
ENROLLMENT NO: 29
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 30
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Program
#include <wiringPi.h>
#include <stdio.h>
int LED = 26; /* GPIO26 as per wiringPi, GPIO12 as per BCM, pin
no.32 */
int main(){
wiringPiSetup(); /* initialize wiringPi setup */
pinMode(LED,OUTPUT); /* set GPIO as output */
while (1){
digitalWrite(LED,HIGH); /* write high on GPIO */
delay(1000);
digitalWrite(LED, LOW); /* write low on GPIO */
delay(1000);
}
}
Now, we should compile above C program with wiringPi library which is given as
follows.
The above command will create an executable file of name led_blink. Then, use
following command to execute above program.
ENROLLMENT NO: 31
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
sudo ./led_blink
In Raspbian OS, there is an installed Geany Programmer’s Editor. We can use this editor
as an IDE for developing programs and execute them.
ENROLLMENT NO: 32
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
After opening it, create new file and write program in it. To create new file, click on file
and select new option which is shown as follows,
ENROLLMENT NO: 33
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 34
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
● Modify C and Execute commands section for compiling and executing program
using WiringPi Library shown as follows,
ENROLLMENT NO: 35
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Click on OK.
ENROLLMENT NO: 36
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
GPIO (General Purpose Input Output) pins can be used as input or output and allows
raspberry pi to connect with general purpose I/O devices.
ENROLLMENT NO: 37
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Some of the GPIO pins are multiplexed with alternate functions like I2C, SPI, UART etc.
Pin Numbering
We should define GPIO pin which we want to use as an output or input. But Raspberry Pi
has two ways of defining pin number which are as follows:
● GPIO Numbering
● Physical Numbering
In GPIO Numbering, pin number refers to number on Broadcom SoC (System on Chip).
So, we should always consider the pin mapping for using GPIO pin.
ENROLLMENT NO: 38
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
While in Physical Numbering, pin number refers to the pin of 40-pin P1 header on
Raspberry Pi Board. The above physical numbering is simple as we can count pin
numbers on P1 header and assign it as GPIO.
But, still we should consider the pin configuration diagram shown above to know which
are GPIO pins and which are VCC and GND.
In this tutorial, we are going to light an LED. In addition to your Raspberry Pi running
Raspbian, what you will need is:
● A Breadboard
● An LED
● A 330 ohm resistor
● Two Male-Female jumper wires
The Breadboard
With the breadboard in the CamJam EduKit, the top row of holes are all connected
together – marked with red dots. And so are the second row of holes – marked with
blue dots. The same goes for the two rows of holes at the bottom of the breadboard.
ENROLLMENT NO: 39
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
In the middle, the columns of wires are connected together with a break in the middle.
So, for example, all the green holes marked are connected together, but they are not
connected to the yellow holes, nor the purple ones. Therefore, any wire you poke into the
green holes will be connected to other wires poked into the other green holes.
The LED
When you pick up the LED, you will notice that one leg is longer than the other. The
longer leg (known as the ‘anode’), is always connected to the positive supply of the
circuit. The shorter leg (known as the ‘cathode’) is connected to the negative side of the
power supply, known as ‘ground’.LED stands for Light Emitting Diode, and glows when
electricity is passed through it.
LEDs will only work if power is supplied the correct way round (i.e. if the ‘polarity’ is
correct). You will not break the LEDs if you connect them the wrong way round – they
will just not light. If you find that they do not light in your circuit, it may be because they
have been connected the wrong way round.
The Resistor
ENROLLMENT NO: 40
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
You must ALWAYS use resistors to connect LEDs up to the GPIO pins of the Raspberry
Pi. The Raspberry Pi can only supply a small current (about 60mA). The LEDs will want
to draw more, and if allowed to they will burn out the Raspberry Pi. Therefore putting the
resistors in the circuit will ensure that only this small current will flow and the Raspberry
Pi will not be damaged.
Resistors are a way of limiting the amount of electricity going through a circuit;
specifically, they limit the amount of ‘current’ that is allowed to flow. The measure of
resistance is called the Ohm (Ω), and the larger the resistance, the more it limits the
current. The value of a resistor is marked with coloured bands along the length of the
resistor body.
You will be using a 330Ω resistor. You can identify the 330Ω resistors by the colour
bands along the body. The colour coding will depend on how many bands are on the
resistors supplied:
● If there are four colour bands, they will be Orange, Orange, Brown, and then
Gold.
● If there are five bands, then the colours will be Orange, Orange, Black, Black,
Brown.
It does not matter which way round you connect the resistors. Current flows in both
ways through them.
Jumper Wires
ENROLLMENT NO: 41
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Jumper wires are used on breadboards to ‘jump’ from one connection to another. The
ones you will be using in this circuit have different connectors on each end. The end
with the ‘pin’ will go into the Breadboard. The end with the piece of plastic with a hole in
it will go onto the Raspberry Pi’s GPIO pins.
GPIO stands for General Purpose Input Output. It is a way the Raspberry Pi can control
and monitor the outside world by being connected to electronic circuits. The Raspberry
Pi is able to control LEDs, turning them on or off, or motors, or many other things. It is
also able to detect whether a switch has been pressed, or temperature, or light. In the
CamJam EduKit you will learn to control LEDs and a buzzer, and detect when a button
has been pressed. The diagram below left shows the pin layout for a Raspberry Pi
Models A and B (Rev 2 - the original Rev 1 Pi is slightly different), looking at the
Raspberry Pi with the pins in the top right corner. The new 40 pin Raspberry Pi’s shares
exactly the same layout of pins for the top 13 rows of GPIO pins.
ENROLLMENT NO: 42
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
The circuit consists of a power supply (the Raspberry Pi), an LED that lights when the
power is applied, and a resistor to limit the current that can flow through the circuit.
You will be using one of the ‘ground’ (GND) pins to act like the ‘negative’ or 0 volt ends of
a battery. The ‘positive’ end of the battery will be provided by a GPIO pin. Here we will be
ENROLLMENT NO: 43
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
using pin 18. When they are ‘taken high’, which means it outputs 3.3 volts, the LED will
light. Now take a look at the circuit diagram below.
You should turn your Raspberry Pi off for the next bit, just in case you accidentally short
something out.
● Use one of the jumper wires to connect a ground pin to the rail, marked with
blue, on the breadboard. The female end goes on the Raspberry Pi's pin, and
the male end goes into a hole on the breadboard.
ENROLLMENT NO: 44
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
● Then connect the resistor from the same row on the breadboard to a column
on the breadboard, as shown above.
● Next, push the LEDs legs into the breadboard, with the long leg (with the kink)
on the right.
● Lastly, complete the circuit by connecting pin 18 to the right hand leg of the
LED. This is shown here with the orange wire.
The Code
You are now ready to write some code to switch the LED on. Turn on your Raspberry Pi
and open the terminal window.
nano LED.py
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
ENROLLMENT NO: 45
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
GPIO.output(18,GPIO.LOW)
Once you have typed all the code and checked it, save and exit the text editor with “Ctrl +
x” then “y” then “enter”.
You will see the LED turn on for a second and then turn off.
ENROLLMENT NO: 46
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Interfacing Diagram
Example
ENROLLMENT NO: 47
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now, let’s control the LED using a switch connected to the Raspberry Pi. Here, we are
using Python and C (WiringPi) for LED ON-OFF control.
Now, let’s turn ON and OFF an LED using Python on Raspberry Pi. Switch is used to
control the LED ON-OFF.
Python Program
while True:
if(GPIO.input(Switch_input)):
GPIO.output(LED,GPIO.LOW)
else:
GPIO.output(LED,GPIO.HIGH)
Functions Used:
RPi.GPIO
To use Raspberry Pi GPIO pins in Python, we need to import RPi.GPIO package which
has class to control GPIO. This RPi.GPIO Python package is already installed on
Raspbian OS. So, we don’t need to install it externally. Just, we should include library in
our program to use functions for GPIO access using Python. This is given as follows.
ENROLLMENT NO: 48
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
This function is used to define Pin numbering system i.e. GPIO numbering or Physical
numbering.
E.g. If we use pin number 40 of P1 header as a GPIO pin which we have to configure as
output then,
In BCM,
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
In BOARD,
GPIO.setmode(GPIO.BOARD)
GPIO.setup(40, GPIO.OUT)
ENROLLMENT NO: 49
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
● GPIO as Output
GPIO.setup(channel, GPIO.OUT)
● GPIO as Input
GPIO.setup(channel, GPIO.IN)
GPIO.output(channel, state)
e.g.
GPIO.output(7, GPIO.HIGH)
GPIO.input(channel)
e.g.
GPIO.input(9)
ENROLLMENT NO: 50
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
We can access Raspberry Pi GPIO using C. Here, we are using WiringPi library for
accessing Raspberry Pi GPIO using C.
Before implementing LED blinking using wiringPi, you can refer How to use WiringPi
library.
Program
#include <wiringPi.h>
#include <stdio.h>
int LED = 26; /* GPIO26 as per wiringPi, GPIO12 as per BCM,
pin no.32 */
int switch_input = 21; /* GPIO21 as per WiringPi, GPIO5 as per
BCM, pin no.29 */
int main(){
wiringPiSetup(); /* initialize wiringPi setup */
pinMode(LED,OUTPUT); /* set GPIO as output */
pullUpDnControl(switch_input, PUD_UP);
while (1){
if(digitalRead(switch_input))
digitalWrite(LED,LOW); /* write LOW on GPIO
*/
else
digitalWrite(LED, HIGH); /* write HIGH on GPIO */
}
}
ENROLLMENT NO: 51
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Introduction
DHT11 Sensor
DHT11 sensor measures and provides humidity and temperature values serially over a
single wire.
It can measure relative humidity in percentage (20 to 90% RH) and temperature in
degree Celsius in the range of 0 to 50°C.
It has 4 pins; one of which is used for data communication in serial form.
Pulses of different TON and TOFF are decoded as logic 1 or logic 0 or start pulse or end
of a frame.
For more information about the DHT11 sensor and how to use it, refer the topic DHT11
sensor in the sensors and modules topic.
Interfacing diagram
ENROLLMENT NO: 52
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Example
Here, we are going to interface DHT11 sensor with Raspberry Pi 3 and display Humidity
and Temperature on terminal.
We will be using the DHT Sensor Python library by Adafruit from GitHub. The Adafruit
Python DHT Sensor library is created to read the Humidity and Temperature on
raspberry Pi or Beaglebone Black. It is developed for DHT series sensors like DHT11,
DHT22 or AM2302.
Extract the library and install it in the same root directory of downloaded library by
executing following command,
ENROLLMENT NO: 53
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Once the library and its dependencies has been installed, open the example sketch
named simpletest from the library kept in examples folder.
In this code, raspberry Pi reads Humidity and Temperature from DHT11 sensor and
prints them on terminal. But, it read and display the value only once. So, here we made
change in the program to print value continuously.
Note:
Assign proper sensor type to the sensor variable in this library. Here, we are using
DHT11 sensor.
sensor = Adafruit_DHT.DHT11
Also, comment out Beaglebone pin definition and uncomment pin declaration for
Raspberry Pi.
Then assign pin no. to which DHT sensor’s data pin is connected. Here, data out of
DHT11 sensor is connected to GPIO4. As shown in above interfacing diagram.
Python Program
#!/usr/bin/python
import Adafruit_DHT
ENROLLMENT NO: 54
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11
#pin = 'P8_11'
# connected to GPIO4.
pin = 4
# Try to grab a sensor reading. Use the read_retry method which will retry up
while True:
ENROLLMENT NO: 55
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
DHT11 Output
ENROLLMENT NO: 56
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Introduction
PIR sensor is used for detecting infrared heat radiations. This makes them useful in the
detection of moving living objects that emit infrared heat radiations.
The output (in terms of voltage) of PIR sensor is high when it senses motion; whereas it
is low when there is no motion (stationary object or no object).
PIR sensors are used in many applications like for room light control using human
detection, human motion detection for security purpose at home, etc.
For more information on PIR sensor and how to use it, refer the topic PIR Sensor in the
sensors and modules section.
ENROLLMENT NO: 57
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Interfacing Diagram
Example
ENROLLMENT NO: 58
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
When motion is detected, PIR output goes HIGH which will be read by Raspberry Pi. So,
we will turn on LED when motion is detected by PIR sensor.
Here, LED is connected to GPIO12 (pin no. 32) whereas PIR output is connected to
GPIO5 (pin no. 29). Let’s write a python based program to interface PIR motion sensor
with Raspberry Pi. To know more about how to access GPIO on Raspberry Pi, you can
refer Raspberry GPIO Access.
Python Program
'''
http://www.electronicwings.com
'''
GPIO.setwarnings(False)
GPIO.setup(PIR_input, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, GPIO.LOW)
ENROLLMENT NO: 59
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
while True:
if(GPIO.input(PIR_input)):
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)
ENROLLMENT NO: 60
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Introduction
Pi Camera module is a camera which can be used to take pictures and high definition
video.
Raspberry Pi Board has CSI (Camera Serial Interface) interface to which we can attach
PiCamera module directly.
This Pi Camera module can attach to the Raspberry Pi’s CSI port using 15-pin ribbon
cable.
Features of Pi Camera
Here, we have used Pi camera v1.3. Its features are listed below,
● Resolution – 5 MP
ENROLLMENT NO: 61
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 62
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now, we can use Pi Camera for capturing images and videos using Raspberry Pi.
For enabling camera in Raspberry Pi, open raspberry pi configuration using following
command,
sudo raspi-config
then select Interfacing options in which select camera option to enable its functionality.
Now we can capture images and videos using Pi Camera on Raspberry Pi.
Example
ENROLLMENT NO: 63
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
We can capture images using Python. Here, we will write a Python program to capture
images using Pi Camera on Raspberry Pi.
Here, we have used picamera package(library) which provides different classes for
Raspberry Pi. Out of which we are mainly interested in PiCamera class which is for
camera module.
'''
capture images on Raspberry Pi using Pi Camera
http://www.electronicwings.com
'''
import picamera
from time import sleep
Functions Used
ENROLLMENT NO: 64
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
To use picamera python based library we have to include it in our program as given
below
import picamera
This picamera library has PiCamera class for camera module. So, we have to create
object for PiCamera class.
PiCamera Class
To use Pi Camera in Python on Raspberry Pi, we can use PiCamera class which has
different APIs for camera functionality. We need to create object for PiCamera class.
The above PiCamera class has different member variables and functions which we can
access by simply inserting a dot (.) in between object name and member name.
capture()
E.g. Camera.capture(“/home/pi/image.jpeg”)
The capture() function has different parameters which we can pass for different
operations like resize, format, use_video_port, etc.
resolution= (width,height)
It sets the resolution of camera at which image captures, video records and preview will
display. The resolution can be specified as (width, height) tuple, as a string formatted
ENROLLMENT NO: 65
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
E.g.
Camera.resolution = “720p”
Camera.resolution = “HD”
Annotate_text = “Text”
start_preview()
Example Camera.start_preview()
stop_preview()
E.g. Camera.stop_preview()
Note: There are various APIs of PiCamera class. So, to know more API in detail you can
refer
PiCamera APIs.
ENROLLMENT NO: 66
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
'''
Record video on Raspberry Pi using pi Camera
http://www.electronicwings.com
'''
import picamera
from time import sleep
camera = picamera.PiCamera()
camera.resolution = (640, 480)
print()
#start recording using pi camera
camera.start_recording("/home/pi/demo.h264")
#wait for video to record
camera.wait_recording(20)
#stop recording
camera.stop_recording()
camera.close()
print("video recording stopped")
Functions used
We have to create object for PiCamera class. Here, we have create object as camera.
start_recording()
E.g. Camera.start_recording(‘demo.h264’)
wait_recording(timeout)
ENROLLMENT NO: 67
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
E.g. Camera.wait_recording(60)
stop_recording()
E.g. Camera.stop_recording()
omxplayer video_name
ENROLLMENT NO: 68
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Blynk is an IoT Platform to control Arduino, Raspberry Pi, NodeMCU and other
microcontrollers over the Internet. Blynk app is a digital dashboard where you can build
a graphic interface for any IoT based project by simply dragging and dropping widgets.
Its simple and easy to use this IoT platform to build complex applications. Blynk is not
bounded to some specific board or platform, but it can be used with any microcontroller,
provided that the microcontroller is connected to internet. Raspberry Pi has inbuilt Wi-Fi
and other microcontroller like Arduino can be connected to internet using some Wi-Fi
module like ESP8266 etc.
Components Required
● Raspberry pi
● Blynk App
● LED
● Resistor(250 ohm)
● Jumper Wires
● Breadboard
Circuit Diagram
ENROLLMENT NO: 69
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
The connections of this project is very simple. Just connect LED’s positive pin to
raspberry Pi’s 3rd (GPIO2) pin and negative pin to resistor.
To control LED with Blynk app, first download and install the Blynk app from Google or
Apple app store. After installing, if you don’t have an account already then create a new
account by entering your Email and password.
ENROLLMENT NO: 70
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
2. Now give your project a name in name slot. Blynk works with hundreds of hardware
models and connection types so choose your device from options. I am here using
Raspberry Pi 3B, so I am proceeding with Raspberry PI 3 B, you can choose different
board. Then after choosing your board choose your connection type whether it is Wi-Fi
or Ethernet or USB connection. After these steps click on ‘Create’ button to create your
project.
ENROLLMENT NO: 71
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
3. Now after this you’ll see a blank new project. To add Widgets to the project click on
Add button (Plus sign button)
ENROLLMENT NO: 72
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 73
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
5. Now in button settings give a name to your button. After this in ‘OUTPUT’ choose your
pin where you connected your Led’s positive pin. Then give names to your On/Off labels.
ENROLLMENT NO: 74
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 75
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
After doing all these steps now put your ‘Auth Token’ in terminal using this command:
After doing all these steps now your Raspberry pi is connected with your Blynk project.
ENROLLMENT NO: 76
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
To run the project click on ‘play button’ on upper right corner. Then Press the button on
Blynk app and watch the LED.
ENROLLMENT NO: 77
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 78
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
IoT is one of the most hyped technologies at the moment. A number of IoT platforms
like Adafruit IO, Blynk, Particle, IFTTT, Artik, Firebase, Thingspeak and etc. are now
available and Cayenne is one of them. But Cayenne is a good choice for a number of
reasons liks:
● To setup Cayenne is faster and easy, as it connects with Pi within few minutes.
● In Cayenne, we can add sensors, motors, actuators, GPIO boards, and more to
control them remotely.
● Cayenne have customizable dashboards with drag-and-drop widgets for different
connected devices.
● We can create triggers and threshold alerts for devices, events, and actions.
● Easy to automate the process for one or multiple devices.
1. The first component is the Cayenne agent software that runs on the RaspberryPi,
and responsible for communicating with the server.
2. The second component is the Cayenne cloud that processes and stores user and
sensor data from the device.
3. The third component is the online dashboard that provides a graphical
environment for working with your IoT project, as well as monitoring and
managing the device.
4. And finally the fourth component is the Cayenne app for Android and IOS is used
to set up and manage Cayenne on the Rasp Pi.
In this project, we are going to set up Raspberry Pi for Cayenne. Below is all the
components that will be needed for setting up myDevices Cayenne for Raspberry Pi.
Components Required
Hardware
● Raspberry Pi
ENROLLMENT NO: 79
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Software
● Cayenne Software
Start with creating an account on myDevices Cayenne. Scroll down and click on ‘TRY IT’
to sign up for a free account.
After sign up, it will redirect you to a new window, where you have to choose a device to
connect with the Cayenne platform. Choose Raspberry Pi.
ENROLLMENT NO: 80
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
In the next window, you will get two options to connect the Pi with your account.
The first option is to connect pi using Cayenne smartphone app and second is using
Raspberry Pi Terminal.
Case 1
To connect it with a smartphone, download Cayenne app from play store and log in.
Now to add a device by clicking on ‘Add Device’ and in next window click on Raspberry
Pi.
ENROLLMENT NO: 81
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now it will search for the available device (make sure that your pi is turned on and
connected to WiFi ).
ENROLLMENT NO: 82
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now click on the connected device, it will take you to the dashboard.
Case 2
wget https://cayenne.mydevices.com/dl/rpi_udkat8fjaw.sh
ENROLLMENT NO: 83
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now we will control led from Cayenne dashboard. Connect the LED as shown in below
circuit diagram:
ENROLLMENT NO: 84
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
ENROLLMENT NO: 85
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now go to GPIO 17 pin and click on input, and change it to output. Then to change led
state click on ‘LOW’ button, it will change to ‘HIGH’. Now your LED is on.
ENROLLMENT NO: 86
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now click on ‘Light Switch’ and fill the details as shown in below image. Then click on
Add Widget.
ENROLLMENT NO: 87
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
It will redirect you to dashboard. Now you will see a button is added to your dashboard
to control the LED.
ENROLLMENT NO: 88
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
IFTTT (If This Then That) is a free IoT service that allows you to send a trigger from one
device/thing, and allow that trigger to make something happen elsewhere.
Confusing? Perhaps, but a quick example should help show the simplicity of it:
Our recipe ('applet') could be: "If I send an email with the subject 'turn on', then switch on
my smart lightbulb".
The 'THIS' is the email and the 'THAT' is lighting the WiFi lightbulb. Simple right?
IFTTT Services
The exciting thing about IFTTT is the sheer number of services you can use as either
triggers (THIS) or actions (THAT). There are hundreds to make use of including Google
Drive, Pushbullet and Android Wear. There are even niche services which can link to your
smart washing machine, Dominos Pizza, BMW and Tesco shopping!
Now imagine if we could combine the power of IFTTT with the Raspberry Pi?
Considering the flexibility of Python, the power of the GPIO, and the huge range of
sensors, components and inputs we can attach to it - the possibilities are truly endless!
ENROLLMENT NO: 89
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
IFTTT Webhooks
Well, this IS possible thanks to the IFTTT Webhooks service, which was specifically
designed for makers.
Webhooks can send and receive triggers via HTML POST and GET requests, which can
be easily added to your code using the 'requests' python library.
A GET request pulls data from a source/server, and a POST request does the opposite -
it sends (or updates) data to a server.
ENROLLMENT NO: 90
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
To explain how to use IFTTT, we're going to show you a real project in action using a
Raspberry Pi Zero W and one of our affordable PIR sensors (also included in our EduKit
Sensors Kit ).
Our IFTTT project will use the Webhooks service as the trigger, which will be used in
conjunction with the Pushbullet service to send a pop-up notification to our smartphone
when that even occurs.
This project will detect when someone enters a room - catching anyone snooping where
they shouldn't be when we're out of the house! This could be used in an office that the
kids aren't allowed in, watching for your little sister borrowing your things, or even as a
super simple DIY Raspberry Pi burglar alarm!
We can even use the IFTTT mobile app to turn the triggers on/off, so that you don't get
constant notifications when you're at home.
ENROLLMENT NO: 91
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Step 1: Assumptions
Before we go anywhere near our Raspberry Pi we need to set up our IFTTT and
Pushbullet accounts.
IFTTT
ENROLLMENT NO: 92
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Go to the IFTTT website (https://ifttt.com) and select 'sign up' in the top-right corner:
It's a straightforward sign-up process like any other - we chose to sign in with our
Google account to remove the need to remember yet another password.
It'll show a screen asking you to pick 3 services to start off with - ignore that and just
click the 'X' in the top-right corner.
You'll then be taken to the homepage - that's it, IFTTT account created!
Pushbullet
ENROLLMENT NO: 93
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
You'll then be taken through some recommended setup steps. You'll want to add the
mobile app for Pushbullet as this is how we receive notifications on our phone.
Select the 'Set up your phone' option, then select either the Android or iPhone. This will
take you to the respective app store page where you can download the Pushbullet app.
ENROLLMENT NO: 94
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Be sure to open the mobile app and log in with the same method (Google/Facebook)
that you used on the desktop site.
The other Pushbullet setup options can be ignored for now. Your Pushbullet account is
now created!
Open IFTTT in a browser, select your username in the top-right corner, then select
'Services'.
You should see a small selection of services - these are the default services that all
users start with. At the bottom of the page, select 'all services'.
ENROLLMENT NO: 95
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
When the next page appears, type 'Webhooks' into the filter box, which will single out the
webhooks service:
ENROLLMENT NO: 96
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Select the Webhooks icon, then click 'connect' on the next screen to enable that
channel.
There's nothing to sign in to for this one, as it's simply activating a way to request and
push data to IFTTT.
The page will refresh and you'll notice a 'Documentation' button appear on the right.
Select that to find your unique 'key' (take a note of it):
Go back to the IFTTT homepage and repeat the steps to add a service, however this
time filter for 'Pushbullet'. As before, you'll see a button to connect IFTTT to the
Pushbullet service.
Assuming you're still signed in to Pushbullet, you should see the following page where it
asks you to approve the request for IFTTT to connect to your Pushbullet account:
ENROLLMENT NO: 97
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
An Applet is our recipe that links services together - linking a 'THIS' trigger with a 'THAT'
action.
For this project, the PIR sensor will trigger the Raspberry Pi to send a HTML POST
request to the IFTTT webhooks service, and will trigger Pushbullet to send a note when
that happens. That will then pop up on your phone as you have the Pushbullet
application installed.
From the IFTTT home page, select the 'My Applets' link at the top of the page. You'll see
the screen below, along with any default applets that IFTTT sets up for new users.
Select the 'New Applet' button on the right side of the screen.
ENROLLMENT NO: 98
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
An easy to use interface will load on your screen. Select the blue 'THIS' link.
Now search for 'Webhooks' and then select the Webhooks icon.
There's only one trigger option for Webhooks, which is 'Receive a web request'. Select
that option:
ENROLLMENT NO: 99
ITM UNIVERSE, VADODARA
COMPUTER SCIENCE & ENGINEERING
Now we need to add some specifics to this trigger. The next screen will ask for an event
name. This is something we add to the Python HTML request later on when we write the
script on the Raspberry Pi.
You'll see the Webhooks icon has now taken the place of the 'THIS' text. We now have to
set the 'THAT' action - click on the blue 'THAT' text:
Using the filter again, type in 'Pushbullet' then select the Pushbullet icon when it
appears. We want Pushbullet to send us a note (a notification) when this applet triggers,
so select the first 'Push a note option'.
We can set this up how we like, including 'ingredients' which are pieces of data which
we can set our Raspberry Pi to send through with our Webhooks request.
We'll keep this one simple and just push some text with the date/time of when motion
was detected, as follows:
Here we see a summary of our applet and confirm that we want to complete it. Select
the 'Finish' button:
That's it - our applet is waiting for us to trigger it from our Raspberry Pi, so let's move to
that part now.
then
Pip is a package manager for Python. You will likely already have pip installed on your
Raspberry Pi, but let's check anyway just in case.
Requests is the module which allows us to send the HTML POST request to IFTTT.
If you're using Raspbian Lite, you may also need to install RPi.GPIO. Type the following
command followed by enter:
As we're using the PIR sensor from the CamJam EduKit Sensors kit, the Python script
is based mostly on the CamJam code for that sensor. We tweaked the layout/style it a
little, and then added just two lines of code to send the POST request to IFTTT:
The Code
Here's the full Python script. Below the code you'll see how to easily download this
directly to your Raspberry Pi:
#! /usr/bin/python
# Imports
import time
import requests
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pinpir = 17
GPIO.setup(pinpir, GPIO.IN)
currentstate = 0
previousstate = 0
try:
while GPIO.input(pinpir) == 1:
currentstate = 0
print(" Ready")
while True:
currentstate = GPIO.input(pinpir)
print("Motion detected!")
# Your IFTTT URL with event name, key and json parameters (values)
r=
requests.post('https://maker.ifttt.com/trigger/YOUR_EVENT_NAME/with/key/YOUR_KE
Y_HERE', params={"value1":"none","value2":"none","value3":"none"})
previousstate = 1
time.sleep(120)
print("Ready")
previousstate = 0
time.sleep(0.01)
except KeyboardInterrupt:
print(" Quit")
GPIO.cleanup()
The easiest way to download the Python script to your Raspberry Pi is with a simple
'wget' command, which tells your Raspberry Pi to download the script.
First, in a terminal window, make a new directory by typing the command below
followed by enter:
mkdir IFTTT
Then enter that directory by using the following command, again followed by enter:
cd IFTTT
Finally, download the script to that directory by using the following command, followed
by enter:
wget https://cdn.shopify.com/s/files/1/0176/3274/files/iftttpir.py
ls
Pro Tip!
Did you notice at the end of line 46 there is a 'params' line of code after the URL?
params={"value1":"none","value2":"none","value3":"none"})
We're not using them in this example, however they can be used to send up to 3 values
to IFTTT in your POST request, which can be any string that your script can create.
Here's where you add them in IFTTT, when you're creating your applet:
Consider the uses of these values when combined with other sensors such as
temperature, ultrasonic or humidity (or one of the many other sensors available)!
To run your code, first make sure you're in the IFTTT directory, then run the code with
this command, followed by enter:
With your code running, you will start receiving notifications from Pushbullet every time
someone moves in front of your PIR sensor!
The script includes a 120-second delay after motion is detected, just to make sure you
don't keep receiving notifications every second when there's someone in the room. You
can change that setting to fit your project's needs (line 53).