IoT Lab MANUAL - R20 Regulations - VCE - 17-8-22

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INTERNET OF THINGS (IOT) – LAB EXPERIMENTS

2023-24 – R20 Regulations

Lab Experiments For IoT Using Raspberry Pi3 :

Week-1

Experiment 1: Read your name and print Hello message with name using Python
Programming

Experiment 2: Read two numbers and print their sum, difference, product and
division using Python Programming

Experiment 3: Word and Characters and Space count of a given string using
Python Programming

Experiment 4: Area of a given shape (rectangle, triangle and circle) reading


shape and appropriate values from a standard input using Python Programming

Week-2

Experiment 5: Print name n times where name and n are read from standard input
using WHILE loops using Python Programming

Experiment 6: Print name n times where name and n are read from standard input
using FOR loop using Python Programming

Experiment 7: Handle Divided by Zero Exception using Python Programming

Experiment 8: Print current time for 10 times with an interval of 10 seconds using
Python Programming

1
Week-3

Experiment 9: Read a file line by line and print the word count of each line using
Python Programming

Experiment 10: LED Blinking ON/OFF using Raspberry Pi3

Experiment 11: Multiple LED Blinking ON/OFF using Raspberry Pi3

Experiment 12: Buzzer Beep with Raspberry Pi3

Week-4

Experiment 13: IR Sensor to Detect Object using Raspberry Pi3

Experiment 14: IR Sensor to Detect Object with LED using Raspberry Pi3

Week-5

Experiment 15: PIR Sensor motion Detection using Raspberry Pi3

Experiment 16: PIR Sensor Motion Detection (Cloud Based) using Raspberry Pi3

Week-6

Experiment 17: DHT11 Temperature & Humidity Sensor using Raspberry Pi3

Experiment 18: DHT11 Temperature & Humidity Sensor (Cloud Based) using
Raspberry Pi3

Week-7

Experiment 19: Temperature & Humidity of CPU Data (Cloud Based) using
Raspberry Pi3

Experiment 20: Smoke Sensor using Raspberry Pi3

Experiment 21: Sound Sensor using Raspberry Pi3

Week-8

Experiment 22: Ph Sensor for detect moisture levels in soil using Raspberry Pi3

2
Week-9

Experiment 23: Implement an Intruder system that sends an alert to the given E-
mail using Raspberry Pi

Week-10

Experiment 24: Get an alarm from a remote area (through LAN) if smoke is
detected.

Week-11

Experiment 25: Create communication Using Raspberry pi and Telegram app.


.

Week-12

Experiment 26: Home Automation System for On/Off LED Bulb

Week-13

Experiment 27: Create communication Using Raspberry pi and Telegram app

3
IOT LAB EXPERIMENTS

Week-1

Experiment 1: Read your name and print Hello message with name using
Python Programming
$sudo nano hello.py

print("Welcome to the get to know your Program in Raspberry Pi")

name = input("what is your name?")

print("Hello", name)

$sudo python3 hello.py

Welcome to write a program in Raspberry Pi

what is your name? "subrahmanyam"

Hello "subrahmanyam"

Experiment 2: Read two numbers and print their sum, difference, product
and division using Python Programming
$sudo nano ASMD.py

x = int(input("Enter a first number"))


y = int(input("Enter a second number"))
print("The addition of these 2 numbers=", x + y,"\n")

#SUBTRACTION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The subtraction of these 2 numbers=", x - y,"\n")

#MULTIPLICATION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The multiplication of these 2 numbers=", x * y,"\n")

#DIVISION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The DIVISION of these 2 numbers=", x / y,"\n")

4
$sudo python3 ASMD.py

Enter a first number 10


Enter a second number15
The addition of these 2 numbers= 25

Enter a first number10


Enter a second number3
The subtraction of these 2 numbers= 7

Enter a first number20


Enter a second number2
The multiplication of these 2 numbers= 40

Enter a first number30


Enter a second number2
The DIVISION of these 2 numbers= 15.0

Experiment 3: Word and Characters and Space count of a given string using
Python Programming
$sudo nano WCP.py

wordCount=0
charCount=0

str=input("Enter the string\n")


split_str=str.split()

wordCount=len(split_str)

for word in split_str:

charCount+=len(word)
print("Total words in the given string ",wordCount)
print("Total characters in the given string ",charCount)
print("Number of space in the given string ",(wordCount-1))

$nano python3 WCP.py


Enter the string
We are learning python in raspberry pi
Total words in the given string 7
Total characters in the given string 32
Number of space in the given string 6

5
Experiment 4: Area of a given shape (rectangle, triangle and circle) reading
shape and appropriate values from a standard input using Python
Programming
$sudo nano RTC.py
import math
r=float(input("Enter the radius"))
ac=math.pi* r*r
print("The area of circle is", ac)
s=float(input("Enter the side of the square"))
sq=s*s
print("The area of square is", sq)
l=float(input("Enter the length of the rectable"))
b=float(input("Enter the breadth of the rectable"))
ar=l*b
print("The are of the rectangle", ar)
base=float(input("Enter the base of the traingle"))
h=float(input("Enter the height of the traingle"))
t=(1/2)*base*h
print("The are of the traingle",t)

$sudo python3 RTC.py


Enter the radius5.6
The area of circle is 98.52034561657591
Enter the side of the square6
The area of square is 36.0
Enter the length of the rectable5.5
Enter the breadth of the rectable2.5
The are of the rectangle 13.75
Enter the base of the traingle3.5
Enter the height of the traingle1.5
The are of the triangle 2.625

6
Week-2

Experiment 5: Print name n times where name and n are read from standard
input using WHILE loops using Python Programming
$sudo nano printname.py

a = input("Enter your name: ")


n = int(input("Enter the number you want to print that times:
"))
i = 1
while i <= n:
print(a)
i+=1

$sudo python3 printname.py

Enter your name: Student


Enter the number you want to print that times: 5
Student
Student
Student
Student
Student

Experiment 6: Print name n times where name and n are read from standard
input using FOR loop using Python Programming

$sudo nano printname.py

a = input("Enter your name: ")


n = int(input("Enter the number you want to print that times:
"))
i = 1
for i in range(5):
print(a)
i+=1

$sudo python3 printname.py

Enter your name: Student


Enter the number you want to print that times: 5
Student

7
Student
Student
Student

Experiment 7: Handle Divided by Zero Exception using Python Programming


$sudo nano zeroexception.py
try:
print (1/0)
except ZeroDivisionError:
print ("You can't divide by zero!")

$sudo python3 zeroexception.py


You can't divide by zero!

Experiment 8: Print current time for 10 times with an interval of 10 seconds


using Python Programming
$sudo nano timedisplay10.py

import time
from datetime import datetime

#For 10 times
for x in range(10):
# Get current time
now = datetime.now()
# Make a string of it
current_time = now.strftime("%H:%M:%S")
# Print it
print(current_time)

# Wait for 10 seconds


time.sleep(10)

$sudo python3 timedisplay10.py


14:32:56
14:33:06
14:33:16
14:33:26
14:33:36
14:33:46
14:33:56
14:34:06
14:34:16
14:34:16

8
Week-3

Experiment 9: Read a file line by line and print the word count of each line
using Python Programming
$ sudo nano file.py
file_name = input("Enter file name:")

file1 = open(file_name, "r")

word_count = 0
i = 0
str1 = ""
print("Contents of file " + file_name + " are:")

# display and count number of words in each line of text file


for line in file1:
i+=1
print(line, end='')
words_in_line = len(line.split())
str1 = str1 + "Words in Line No: " + str(i) + " are : " +
str(words_in_line)+"\n"
word_count+=words_in_line

print('\n\n ' + str1)


print('\n\nTotal Number of words in this file are = ' +
str(word_count))

file1.close()

$sudo python3 timedisplay10.py


Enter file name:text
Contents of file text are:
hellow hellow hellow
hellow hellow hellow
hellow hellow hellow hellow hellow hellow hellow hellow hellow
hellow hellow hellow
hellow hellow hellow

Words in Line No: 1 are : 3


Words in Line No: 2 are : 3
Words in Line No: 3 are : 7
Words in Line No: 4 are : 3
Words in Line No: 5 are : 3

9
Experiment 10: LED Blinking ON/OFF using Raspberry Pi3
We will need the following tools to complete the project:

 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


 Solderless breadboard
 Jumper wires for easy hookup
 Resistor pack
 Red LED

Step1- Project design with circuit

The first step in this project is to design a simple LED circuit. Then we will make the
LED circuit controllable from the Raspberry Pi by connecting the circuit to the general
purpose input/output (GPIO) pins on the Raspberry Pi.

Step2- Connect LED bulb, resistor in Breadboard

 A simple LED circuit consists of a LED and resistor.


 The resistor is used to limit the current that is being drawn and is called a current
limiting resistor. Without the resistor the LED would run at too high of a voltage,
resulting in too much current being drawn which in turn would instantly burn the
LED, and likely also the GPIO port on the Raspberry Pi.
 When hooking up the circuit note the polarity of the LED. You will notice that the
LED has a long and short lead.
 The long lead is the positive side also called the anode, the short lead is the
negative side called the cathode.
 The long should be connected to the resistor and the short lead should be
connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as
shown on the diagram.

10
Step3- To find the pin number refer to this diagram showing the physical pin
numbers on the Raspberry Pi.

Pin=8(GPIO) Pin=39 (GRD)


Short terminal (+) Short terminal (-)

11
Step4- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano LED_Blink.py

To run the python program using following command:

$sudo python3 LED_Blink.py

import RPi.GPIO as GPIO #import RPi.GPIP module

import time #time factor is for time taken for LED of/off

GPIO.setmode(GPIO.BOARD) #board method using

GPIO.setup(8,GPIO.OUT) # for input of LED using GPIO pin

for x in range(5): # 5 times LED will blink on/off

GPIO.output(8,True) #GPIO 8 pin is enable

print("LED is ON") #LED is ON

time.sleep(1) #time taken for LED ON 1 second

GPIO.output(8,False) #GPIO 8 pin is enable

print("LED is OFF") #LED is OFF

time.sleep(1) #time taken for LED OFF 1 second

Output:

LED is ON

LED IS OFF

12
Experiment 11: Multiple LED Blinking ON/OFF using Raspberry Pi3
We will need the following tools to complete the project:

 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


 Solderless breadboard
 Jumper wires for easy hookup
 Resistor pack
 Red LED and Blue LED

Step1- Project design with circuit

The first step in this project is to design a simple LED circuit. Then we will make the
LED circuit controllable from the Raspberry Pi by connecting the circuit to the general
purpose input/output (GPIO) pins on the Raspberry Pi.

Step2- Connect 2 - LED Bulbs, resistor in Breadboard

 A simple LED circuit consists of a LED and resistor.


 The resistor is used to limit the current that is being drawn and is called a
current limiting resistor.
 Without the resistor the LED would run at too high of a voltage, resulting in too
much current being drawn which in turn would instantly burn the LED, and likely
also the GPIO port on the Raspberry Pi.
 When hooking up the circuit note the polarity of the LED.
 You will notice that the LED has a long (terminal +) and short(terminal  -)
lead.
 The long lead is the positive side(+) also called the anode, the short lead is the
negative side(-) called the cathode.
 The long should be connected to the resistor and the short lead should be
connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as
shown on the diagram.

13
Step3- To find the pin number refer to this diagram showing the physical pin
numbers on the Raspberry Pi.

14
Step4- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano 2LED_Blink.py

To run the python program using following command:

$sudo python3 2LED_Blink.py

import RPi.GPIO as GPIO #import RPi.GPIP module

import time #time factor is for time taken for LED of/off

GPIO.setmode(GPIO.BOARD) #board method using

GPIO.setup(8,GPIO.OUT) # for input of LED using GPIO pin

GPIO.setup(10,GPIO.OUT) # for input of LED using GPIO pin

while True:

GPIO.output(8,True) #GPIO 8 pin is enable

print("LED is ON") #LED is ON

time.sleep(1) #time taken for LED ON 1 second

GPIO.output(8,False) #GPIO 8 pin is enable

print("LED is OFF") #LED is OFF

GPIO.output(10,True) #GPIO 10 pin is enable

print("LED IS ON") #LED is ON

time.sleep(1) #time taken for LED ON 1 second

GPIO.output(10,False) #GPIO 10 pin is enable

print("LED IS OFF") #LED is OFF

Output:
LED is ON
LED IS OFF

15
Experiment 12: Buzzer Beep with Raspberry Pi3
We will need the following tools to complete the project:

 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


 Solderless breadboard
 Jumper wires for easy hookup
 Buzzer (Active (+) and Passive(-)

Step1

Introduction to Buzzer

A buzzer is a small yet efficient component to add sound features to our project/system.
It is very small and compact 2-pin structure hence can be easily used on breadboad, Perf Board
and even on PCBs which makes this a widely used component in most electronic applications.
There are two types of buzzers that are commonly available. The one shown here is a simple
buzzer which when powered will make a Continuous Beeeeeeppp.... sound, the other type is
called a readymade buzzer which will look bulkier than this and will produce a Beep. Beep.
Beep.
Sound due to the internal oscillating circuit present inside it. But, the one shown here is most
widely used because it can be customized with help of other circuits to fit easily in our
application.
Step2

How to use a Buzzer

This buzzer can be used by simply powering it using a DC power supply ranging from 4V to 9V.
A simple 9V battery can also be used, but it is recommended to use a regulated +5V or +6V DC
supply.
The buzzer is normally associated with a switching circuit to turn ON or turn OFF the buzzer at
required time and require interval.

16
Step3

Buzzer Pin Configuration

Pin Pin Name Description


Number

1 Positive Identified by (+) symbol or longer terminal lead. Can be powered by 6V DC

2 Negative Identified by short terminal lead. Typically connected to the ground of the
circuit

Step4

Buzzer Features and Specifications

 Rated Voltage: 6V DC
 Operating Voltage: 4-8V DC
 Rated current: <30mA
 Sound Type: Continuous Beep
 Resonant Frequency: ~2300 Hz
 Small and neat sealed package
 Breadboard and Perf board friendly

Step5

Applications of Buzzer

 Alarming Circuits, where the user has to be alarmed about something


 Communication equipments
 Automobile electronics
 Portable equipments, due to its compact size

17
Step6

Experiment: Connecting a Buzzer ON/OFF


An active buzzer can be connected just like an LED, but as they are a little more robust, you
won’t be needing a resistor to protect them.

Set up the circuit as shown below:

Step7- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano Buzzer.py

To run the python program using following command:

$sudo python3 Buzzer.py

18
Step8 - Program:

import RPi.GPIO as GPIO #import RPi.GPIP module

import time #time factor is for time taken for LED of/off

GPIO.setmode(GPIO.BOARD) #board method using

GPIO.setup(8,GPIO.OUT) # for input of LED using GPIO pin

while True:

GPIO.output(8,True) #GPIO 8 pin is enable

print("Buzzer is ON")#Buzzer give beep sound

time.sleep(1) #time taken for Buzzer 1second to beep sound

GPIO.output(8,False) #GPIO 8 pin is enable

print("Buzzer is OFF") #Buzzer silent

time.sleep(1) #time taken for Buzzer 1 second to silent

Output:

Buzzer is ON

Buzzer is OFF

19
Week-4

Experiment 13: Infrared Sensors(IR) Sensor to Detect Object using


Raspberry Pi3
We will need the following tools to complete the project:

 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


 Solderless breadboard
 Jumper wires for easy hookup
 IR Sensor

Step1

Introduction to IR Sensor

Infrared Sensors or IR Sensors are used as Obstacle Detecting Sensors or Proximity


Sensors. Applications where IR Sensors are implemented are Line Follower Robots,
Obstacle Avoiding Robots, Edge Avoiding Robots and many more.

IR Sensors emit and receive Infrared radiation. They are often used as Proximity Sensors
i.e. detect and alarm if an object is close to the sensor.

Step2

Real-Time Applications of IR Sensor

1]Mobile Phones.

Almost all mobile phones nowadays have IR Sensors in them. Usually, they will be
placed near the earpiece on the phone.

When the user make or receives a phone call, the IR Sensor detects how far the phone is
from the user’s ear. If it is close to the ear, the phone’s display will be turned off so that
you do not touch anything on the screen accidently.

2]Automobiles
Another important application is in automobiles. All modern cars are equipped with
reverse parking sensor that sense how far you can reverse your car without hitting
anything. These reverse sensors are implemented using IR Sensors.

20
Step3

Raspberry Pi IR Sensor Interface

IR Sensors emit and receive Infrared radiation. They are often used as Proximity Sensors
i.e. detect and alarm if an object is close to the sensor.

Now that we have seen a little bit about the IR Sensor Module and its connections, we
will proceed with interfacing IR Sensor with Raspberry Pi.

The Raspberry Pi IR Sensor Interface can be converted into a Proximity Detector, where
the application will detect if the object is too close to the sensor.

21
Step4

Circuit Diagram
The following image shows the connection diagram of Interfacing IR Sensor with Raspberry Pi.
You have already seen the circuit diagram of the IR Sensor Module.

22
Step5

Applications

As mentioned in the earlier sections, Proximity Sensor or Obstacle Detection is the main
application of interfacing IR Sensor with Raspberry Pi. Some of the common applications
include:

Line Follower Robot

Obstacles Avoiding Robot

23
Car Reverse Sensor

Mobile Proximity Sensor

24
Step6- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano ir_sensor.py

To run the python program using following command:

$sudo python3 ir_sensor.py

Step7: Program
import RPi.GPIO as GPIO #import RPi.GPIP module

import time #time factor is for time taken for LED of/off

GPIO.setmode(GPIO.BOARD) #board method using

GPIO.setup(8,GPIO.IN) #for input GPIO pin

while True:

if GPIO.input(8)==0:#if input GPIO ==0

print("IR sensor detect the object")#IR sensor detect object

time.sleep(0.1)#time taken for LED ON 1 second

else:

print("IR sensor not detect the object")#IR sensor not


detect object
time.sleep(0.1) #time taken for LED ON 1 second

Output:

IR sensor detect the object

IR sensor not detect the object

25
Experiment 14: Infrared Sensor(IR) Sensor to Detect Object with LED
blinking automatically using Raspberry Pi3
We will need the following tools to complete the project:

 Raspberry Pi 3 setup with monitor and USB Mouse & Keyboard


 Solderless breadboard
 Jumper wires for easy hookup
 IR Sensor
 LED Bulb

Circuit Diagram
The following image shows the connection diagram of Interfacing IR Sensor with Raspberry Pi.

26
Step6- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano ir_sensor_led.py

To run the python program using following command:

$sudo python3 ir_sensor_led.py

Program
import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(8,GPIO.IN)

GPIO.setup(10,GPIO.OUT)

while True:

if GPIO.input(8)==0:

GPIO.output(10,True)

print("IR sensor YES detect the object, led is ON")

time.sleep(0.1)

else:

GPIO.output(10,False)

print("IR sensor NOT detect the object, led is OFF")

time.sleep(0.1)

Output:

IR sensor YES detect the object, led is ON

IR sensor NOT detect the object, led is OFF

27
Week-5

Experiment 15: Passive Infrared Sensor (PIR) Sensor motion Detection using
Raspberry Pi3
Passive Infrared Sensor (PIR – Introduction)
 Passive infrared (PIR) sensors are devices that are used to detect motion. Sometimes they
are referred to as pyroelectric sensors. As the name suggests, the devices are passive
sensors, which means that the sensor does not use energy to detect infrared light.
 A pyroelectric sensor consists of an electrically polarized crystal that generates an electric
charge when exposed to infrared radiation. All animals emit infrared radiation, so PIR
sensors can be used to detect the motion of humans and other large animals.

PIR Working Procedure:

 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.

The sensing element consists of crystals that respond to changes in infrared energy. The sensing
element is split into two parts – sensing element A and sensing element B:

When nothing is moving, the two sensing elements detect the same infrared levels and cancel
each other out. When an infrared emitting object like a dog moves into the sensor’s field of view,
sensing element A detects the infrared light first. This causes a positive differential change
between the two sensing elements because the infrared light level hitting sensor element B is still
low.

28
When the object passes the sensor, the infrared light level hitting sensor element B will be
higher than element A, which causes a negative differential change between the two sensing
elements.

This potential difference is detected and amplified by an onboard logic chip (the BISS0001), and
turned into a digital signal that can be detected by the Raspberry Pi.

PIR sensor can detect animal/human movement in a requirement range. PIR is made of a
pyroelectric sensor, which is able to detect different levels of infrared radiation. The detector
itself does not emit any energy but passively receives it.

The pyroelectric sensor sees the moving human body for a while and then does not see it, so the
infrared radiation of human body constantly changes the temperature of the pyroelectric material.
So that it outputs a corresponding signal, which is the alarm signal.

Plastic optical reflection system or plastic Fresnel lens used as a focusing system for infrared
radiation.

29
Experiment:
The module has three pins: Ground and VCC for powering the module. The Digital Out
Pin gives a high logic level as a target moves within the sensor’s range.

30
Step4- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano LED_Blink.py

To run the python program using following command:

$sudo python3 LED_Blink.py

Program1:

import RPi.GPIO as GPIO

import time

import requests

GPIO.setmode(GPIO.BCM)

pirPin = 4 #pin=7

GPIO.setup(PirPin, GPIO.IN)

time.sleep(1)

while True:

if GPIO.input(pirPin):

print("Motion Detected")

time.sleep(1)

print("No one")

Output:
No One
No One
No One
Motion detected  when any person in move, the PIR sensor
detect motion.

31
Program: 2

import RPi.GPIO as GPIO

PIR_input = 29 #read PIR Output

LED = 32 #LED for signaling motion detected

GPIO.setwarnings(False)

GPIO.setmode(GPIO.BOARD) #choose pin no. system

GPIO.setup(PIR_input, GPIO.IN)

GPIO.setup(LED, GPIO.OUT)

GPIO.output(LED, GPIO.LOW)

while True:

#when motion detected turn on LED

if(GPIO.input(PIR_input)):

GPIO.output(LED, GPIO.HIGH)

else:

GPIO.output(LED, GPIO.LOW)

32
GND = Pin 6
VCC = Pin 1
DATA = Pin 7

VCC DATA GND

33
Week-6

Experiment 17: DHT11 Temperature & Humidity Sensor using Raspberry


Pi3
Hardware Components Requirement:

1. Raspberry Pi3
2. LAN cable
3. Jumper wires
4. Breadboard
5. DHT11 Temperature and Humidity Sensor

Introduction to DHT11

Raspberry Pi DTH11 Humidity and Temperature Sensor Interface

By interfacing the DHT11 Sensor with Raspberry Pi, you can build your own IoT
Weather Station. All you need to implement such IoT Weather is a Raspberry Pi, a
DHT11 Humidity and Temperature Sensor and a Computer with Internet Connectivity.

Applications of DHT11 Temperature and Humidity Sensor

DHT11 Temperature and Humidity Sensor is one of the popular sensor modules used
by hobbyists for implementing in a lot of IoT Projects. This sensor along with
Raspberry Pi can also be used in:

 HVAC (Heat Ventilation and Air Conditioning) Systems


 Thermostats
 Home and Office Climate Control
 Weather Station

34
Circuit Diagram

All you need to do is to connect the VCC and GND pins of the DHT11 Sensor to +5V
and GND of Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4
i.e. Physical Pin 7 of the Raspberry Pi.

35
Installing DTH11 Library

Since we are using a library called Adafruit_DHT provided by Adafruit for this project, we need
to first install this library into Raspberry Pi.

First step is to download the library from GitHub. But before this, I have created a folder called
‘library’ on the desktop of the Raspberry Pi to place the downloaded files. You don’t have to do
that.

Now, enter the following command to download the files related to the Adafruit_DHT library.

git clone https://github.com/adafruit/Adafruit_Python_DHT.git

All the contents will be downloaded to a folder called ‘Adafruit_Python_DHT’. Open


this directory using cd Adafruit_Python_DHT. To see the contents of this folder, use ‘ls’
command.

In that folder, there is file called ‘setup.py’. We need to install this file using the
following command.

$sudo python setup.py install

36
Step4- Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano 1dht.py

To run the python program using following command:

$sudo python3 1dht.py

Program1: Basic program


import sys
import Adafruit_DHT
import time

while True:

humidity, temperature = Adafruit_DHT.read_retry(11, 4)

print 'Temp: {0:0.1f} C


Humidity:{1:0.1f}'.format(temperature, humidity)

time.sleep(1)

Output:

37
Experiment 18: DHT11 Temperature & Humidity Sensor (Cloud Based) using
Raspberry Pi3
To view / edit the python program using following command:

$sudo nano temp.py

import RPi.GPIO as GPIO


import time
import Adafruit_DHT
import urllib.request

pin = 2

while True:
humidity, temperature=Adafruit_DHT.read_retry (Adafruit_DHT.
DHT11,pin)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C
Humidity={1:0.1f}%'.format(temperature,
humidity))
else:
print('Failed to get reading. Try again')

time.sleep(2)

f = urllib.request.urlopen("https://api.thingspeak.com/
update?api_key=1DOQ3MODXLTSQXEZ&field1=%S&field2=%S" %
(temperature, humidity))
print (f.read())
f.close()

$sudo python3 temp.py

38
Week-7

Experiment 19: Temperature of CPU Data (Cloud Based) using Raspberry Pi3
https://www.youtube.com/watch?v=legRoQAxSug

Description: To know real-time temperature of CPU data using Raspberry Pi3

$ sudo nano cpu_temp.py


import commands,time

while True:
templfile-open('/sys/class/thermal/thermal_zone0/temp')
cpu_temp_raw=tempFile.read()
tmpFile.close()
cpu_temp=round(float(cpu_temp_raw)/1000,1)
print cpu_temp
time.sleep(1)

$ sudo python3 cpu_temp.py

47.8

47.8

47.2

47.2

47.3

47.8

47.2

47.2

39
Experiment 20: Smoke Sensor using Raspberry Pi3

Components Needed
 Raspberry Pi board
 MQ-2 Smoke Sensor
 MCP3002 Analog-to-digital Converter Chip

Experiment:

The 3 leads are Output, VCC, and GND.


The gas sensor needs about 5 volts of power in order to operate. This is done by connecting 5
volts to Vcc and GND.
The Output pin gives out the voltage reading, which is proportional to the amount of smoke that
the sensor is exposed to. Again, a high voltage output means the sensor is exposed to a lot of
smoke. A low or 0 voltage output means the sensor is exposed to either little or no smoke.

Circuit for Gas Sensor using Raspberry Pi3

40
Python Code
The code to read the value of a smoke sensor with a Raspberry Pi is shown below.

/* MQ-2 Smoke Sensor Circuit with Raspberry Pi */

To view / edit the python program using following command:

$sudo nano smoke.py

import time
import botbook_mcp3002 as mcp #

smokeLevel= 0

def readSmokeLevel():
global smokeLevel
smokeLevel= mcp.readAnalog()

def main():
while True: #
readSmokeLevel() #
print ("Current smoke level is %i " % smokeLevel) #
if smokeLevel > 120:
print("Smoke detected")
time.sleep(0.5) # s

if_name_=="_main_":
main()

Ouput:
$sudo python3 smoke.py

Smoke detected
Smoke detected

41
Experiment 21: Sound Sensor using Raspberry Pi3
https://www.instructables.com/Sound-Sensor-Raspberry-Pi/

Hardware Components Requirement:

1. Raspberry Pi3
2. LAN cable
3. Jumper wires
4. Breadboard
5. Sound Sensor

VCC <-> 5V
GND <-> GND
D0 <-> GPIO 17

42
Python Code for Sound Detect using Raspberry Pi3

$sudo nano sound.py

#!/usr/bin/python
import RPi.GPIO as GPIO
import time

#GPIO SETUP
channel = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

def callback(channel):
if GPIO.input(channel):
print "Sound Detected!"
else:
print "Sound Detected!"

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when


the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN,
Run function on change

# infinite loop
while True:
time.sleep(1)

$sudo python3 sound.py

Output:
Sound detected
Sound detected
Sound detected
Sound detected
Sound detected
Sound detected

43
Week-8

Experiment 22: Ph Sensor for detect moisture levels in soil using Raspberry Pi3

Aim: Soil moisture sensors measure the volumetric water content in soil with
Raspberry Pi3

Hardware Component:

1. Raspberry Pi X1
2. Soil Moisture Sensor with A-D breakout board X1
3. Female to Female Jumper wires X5

Software Components

1. Python 3.5 (IDLE) integrated development environment

EXPERIMENT

 In this project we will be integrating the Soil Moisture Sensor with the
Raspberry Pi. To connect the sensor to the Pi an Analog to Digital
conversion is required as the sensor produces analog output.
 To convert the Analog to Digital we use a breakout board which comes
along with the sensor. There are 5 connections that are to be made. 3
connections are to the Pi and the other 2 are to the soil sensor.
 The Analog to digital (A-D) breakout board converts the analog output of
the sensor to digital for the pi to understand it. So we have to connect the
digital pin i.e. D0 to the GPIO of the raspberry pi. The pin A0 is kept open
as we are not using it for this project.
 The sensitivity of the sensor can be changed by varying the potentiometer
present on the A-D breakout board. The connections are made as follows:

 Vcc – 5V
 Gnd – Ground
 Signal (D0) – GPIO 21

44
 When the connections are made and the Pi is powered up, a red light on the
A-D breakout board turns on indicating that the board is ready to be used.
For testing purposes take the sensor and dip it in water.
 When around half of the sensor is in the water another light on the breakout
board turns on indicating the presence of water. To check the presence of
moisture in the soil insert the sensor (about 3/4th of the sensor) into the soil
and find out whether moisture is present or not.

CIRCUIT DIAGRAM

Writing the Python Software to blink the LED

To view / edit the python program using following command:

$sudo nano moisture.py

To run the python program using following command:

$sudo python3 moisture.py

45
Program:

import RPi.GPIO as GPIO


from time import sleep

channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)

def callback(channel):
if GPIO.input(channel):
print("No water detected")
else:
print("Water Detected")

GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) #Let us know


when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # Assign function to GPIO
PIN, Run function on change

while True:
sleep(1)

Run the python program

$sudo python3 moisture.py

Result:
pi@raspberrypi:~/MOISTURE $ sudo python3 moisture.py
Water Detected
Water Detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
Water Detected
Water Detected

46
Week-9

Experiment 23: Implement an Intruder system that sends an alert to the given E-
mail using Raspberry Pi
https://circuitdigest.com/microcontroller-projects/raspberry-pi-iot-intruder-alert-system

Hardware Component:
 Raspberry Pi
 Pi Camera
 PIR Sensor
 LED
 Bread Board
 Resistor (1k)
 Connecting wires
 Power supply
Experiment

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.

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.

47
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 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:

48
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

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.

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

49
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

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..." saddam4201@gmail.com
Python 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 = "raspiduino4201@gmail.com" # change the email
address accordingly
toaddr = "saddam4201@gmail.com"
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

50
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)

51
Week-10

Experiment 24: Get an alarm from a remote area (through LAN) if smoke is
detected.
https://www.youtube.com/watch?v=lCcXiFnYCuY

Introduction
A fire sensor is a device that is used to detect fire or flame. It is very important
to use this type of sensors where there is a chance of a fire occurring. We can
use even for our household purposes also where there might be any chances
of occurring fire accidents. So let's get headed towards the project and
understand the working in detail along with the circuit diagram and codes.

Hardware Equipment:
1. Raspberry Pi
2. Fire sensor
3. USB Cable
4. JUMping wires

Hardware Connections:
Fire sensor with Raspberry pi3 and send notifications of your mobile use by
notification service. The fire sensor detect flame and send notification to our
mobile.

The pins are in Fire sensor.

A0

G ---> ground pin connected to ground

VCC+ --> 3.3

D0 --> connect GPIO

52
The fire #sensor has four pins which are A0(analog pin), ground, VCC(can be
3.3v/5v depending on the module), and D0( digital output pin). In addition to these
pins, the module has LEDs for power and D0 output. The D0 led glows when the
sensor detects fire. Also, we have a #potentiometer in the fire sensor which allows
voltage to flow as per the required amount while functioning.

We connect these pins with a raspberry pi board with different pins on it. The D0
pin of the fire sensor is connected to the Raspberry Pi GPIO. The ground and VCC
pin of the fire sensor is connected to the respective terminals of the Raspberry Pi
board.

In the fire sensor, the fourth pin is the analog pin(A0) which can not be connected
to the Raspberry Pi directly. So if one wants to use the analog pin an external
analog to digital converter is required for the Raspberry Pi GPIO

To get notification on your mobile to have to create a account of push login to


account in our gmail.com.

53
Step2: Pushbullet Website

www.pushbullet.com
settings  create access tokens click on (get API copy & paste in code)

Python Code for Fire alert system using Raspberry Pi3


$sudo nano fire_sensor.py

from pushbullet import pushbullet


mport RPi.GPIO as GPIO
import time
channel =4
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel,GPIO.IN)
Pb=Pushbullet(“Your_AP_Token”)
Print(pb.devices)
Def send_pntf(channel):
Print(“sending alert”)
Dev=dev.push_note(“Alert”,”fire at your place”)
Print(“sent”)
GPIO.add_event_detect(channel, GPIO.RISING, bouncetime=120)
GPIO.add_event_callback(channel,send_pntf)
While True:
Time.sleep(60)

To run the python program using following command:

$sudo python3 fire_sensor.py

Output

Fire detected

54
Week-11

Experiment 25: Create communication Using Raspberry pi and Telegram app

https://maker.pro/raspberry-pi/projects/how-to-create-a-telegram-bot-with-a-
raspberry-pi

Introduction:
Learn how to use a Raspberry Pi and the Telegram app to create a bot to help you with tasks
around the house. n this article, we will create a telegram bot capable of sending and receiving
messages from a Raspberry Pi. We’ll program the Raspberry Pi to obtain the time and date. We
will also be able to control the GPIO pins of the Raspberry Pi, by connecting the two LEDs on
the Raspberry Pi GPIO pins.

Telegram is a messaging app like WhatsApp, but Telegram can create the bots. It has an API bot
that not only allows the human to talk to it, but also machines. With this tutorial, you can use
Telegram to control anything in your home or even feed your dog when you’re away.

Required Components for Your Telegram Bot


 Raspberry Pi
 2 LEDs
 2 220 ohm resistors
Installing and Creating Your Telegram Bot
 First, go to the Google Play store and download the Telegram app.
 When you open the app, it will ask for your number. Enter the number, and Telegram
will send a verification code. You will need to enter the code to confirm your account.
 After adding the number, it will take you to the home screen
 Now we need to create a new bot that will send and receive messages with the Raspberry
Pi. Telegram has a BotFather that will help us create a bot. Search for “botfather” in the
app.
 Next write “/start” to start chatting with the bot.
 After that, write “/newbot’ to request a new bot.
 Now it will ask you to name your new bot.
 Next, it will ask for a username for the bot. Enter a unique username to create your bot.
In the message you receive, there will be a token. Save it, as you will need it in the code.
 Next, search for the bot using its to confirm that the bot has been created.
 Finish created bot

We have finished creating the bot. Now, we need to write some code for the Raspberry Pi that
will make it respond to messages from the bot. Before that, hook up the connections for the
Raspberry Pi.

55
Similarly, connect the positive lead of the green LED to GPIO 20 of the Raspberry Pi and the
negative lead of the green LED to the ground through the 220-ohm resistor.

Installing the Correct Library Into Raspbian


We need to install the teleport library into Raspbian. Type the command below in the terminal to
install it:

$sudo pip install teleport

56
Full Telegram Bot With Raspberry Pi Code
import datetime # Importing the datetime library
import telepot # Importing the telepot library
from telepot.loop import MessageLoop # Library function to communicate
with telegram bot
import RPi.GPIO as GPIO # Importing the GPIO library to use the GPIO pins
of Raspberry pi
from time import sleep # Importing the time library to provide the delays
in program

red_led_pin = 21 # Initializing GPIO 21 for red led


green_led_pin = 20 # Initializing GPIO 20 for green led

GPIO.setmode(GPIO.BCM) # Use Board pin numbering


GPIO.setup(red_led_pin, GPIO.OUT) # Declaring the GPIO 21 as output pin
GPIO.setup(green_led_pin, GPIO.OUT) # Declaring the GPIO 20 as output pin

now = datetime.datetime.now() # Getting date and time

def handle(msg):
chat_id = msg['chat']['id'] # Receiving the message from telegram
command = msg['text'] # Getting text from the message
print ('Received:')
print(command)
# Comparing the incoming message to send a reply according to it
if command == '/hi':
bot.sendMessage (chat_id, str("Hi! MakerPro"))
elif command == '/time':
bot.sendMessage(chat_id, str("Time: ") + str(now.hour) + str(":") +
str(now.minute) + str(":") + str(now.second))
elif command == '/date':
bot.sendMessage(chat_id, str("Date: ") + str(now.day) + str("/") +
str(now.month) + str("/") + str(now.year))
elif command == '/red_1':
bot.sendMessage(chat_id, str("Red led is ON"))
GPIO.output(red_led_pin, True)
elif command == '/red_0':
bot.sendMessage(chat_id, str("Red led is OFF"))
GPIO.output(red_led_pin, False)
elif command == '/green_1':
bot.sendMessage(chat_id, str("Green led is ON"))
GPIO.output(green_led_pin, True)
elif command == '/green_0':
bot.sendMessage(chat_id, str("Green led is OFF"))
GPIO.output(green_led_pin, False)
# Insert your telegram token below
bot = telepot.Bot('542543102:AAE7xb6_XGAn9Yh-4PPJmfK5YK9TEA4')
print (bot.getMe())
# Start listening to the telegram bot and whenever a message is received,
the handle function will be called.
MessageLoop(bot, handle).run_as_thread()
print ('Listening....')

while 1:
sleep(10)

57
Week 12

Experiment 26: Home Automation System for On/Off LED Bulb


https://www.youtube.com/watch?v=rDgQZ5c4wdk

Build a simple IoT Home automation project using Raspberry Pi without writing a single line of
Python Code. Use Cayenne to remotely control a Relay connected to the Raspberry Pi which will
turn a LED Bulb ON/OFF based on user input. As cayenne is a cloud platform, we can control
the LED bulb from anywhere in the world as long as the Pi is connect to the Internet.

Step1:
Create your Cayenne myDevices Account here: https://accounts.mydevices.com/

As this is your first login, you will be redirected by default to create a new project.
Select  Raspberry Pi then in step2 before clicking next, make sure your Pi is up and running
and is connected to the Internet.
Now click next
Step2:
Open the terminal in Raspberry Pi and copy & paste the commands given in the Caynne
dashboard.

While installing, the cayenne dashboard will get remote access to your Pi and shows the status of
the installation.

58
Step3:
As soon as the installation process completes, the online dashboard will automatically appear.
Your Raspberry Pi is now ready to use.
Now click "Add new" and then select the “device option” from the submenu.

Select Relay is an actuator select actuators from device list and the select Relay and it shows
Relay switch.

Actuators  Relay  shows Relay switch

Leave the Widget name and device as default. For Connectivity option you need to select it as
integrated GPIO. Next you need to set the channel, which is essentially the GPIO pin that will
be interfaced with the Relay Module. Now Select channel 17.
.
Finally choose the widget type as button and click add actuator.

59
Step4

Once the widget is configured and created you will be redirected to the dashboard overview.

This is where toggle button for controlling the relay will appear. The next step is to interface the
Raspberry Pi to a Relay and then connect the CFL in normally open configuration.

Step5
Jumper wire connection from Relay to Rasbperry Pi.
Connect the VCC pin of the Relay to a 5V pin of the Rasbperry Pi.
GIT pin of Relay to any GND pins of the Rasbperry Pi.
IN1 pin of Relay to GPIO 17 pin of the Rasbperry Pi.

Output
Clicking the Toggle button on the Dashboard indeed actuates the relay which in turn switches the
CFL to ON state. If we select ON the LED bulb automatically On. The LED bulb will be
glowing.
It is an IoT based Home Automation project using Raspberry Pi without writing even a single
line of Python code.

***

60

You might also like