You are on page 1of 58

INTERNET OF THINGS

Lab Manual
VISION AND MISSION OF THE INSTITUTION
Vision
To emerge as a leading Institute for Technical Education and Research in
India with focus to produce professionally competent and socially sensitive
engineers capable of working in multidisciplinary global environment.
Mission
1. To train the students in the fundamentals of Engineering, Science and
Technology by providing good academic environment to pursue
undergraduate, Post graduate in chosen fields of Engineering and
Technology for a successful professional career.

2. To be a continuous learning organization by developing strong liaison


with Academia,       R & D institutions and Industry for exposure in
practical aspects of engineering and providing solutions to the industrial
and societal problems for sustainable development. To imbibe skills for
entrepreneurship, project and finance management.

3. To inculcate team work, leadership, professional ethics, use of modern


tools, IPR issues so that graduates are encouraged to obtain patents and
respond to competitive global environment.

4. To promote strong research culture in graduates for lifelong learning, to


explore the frontiers of knowledge and present at technical fora/publish
in Journals at national/international level.
DEPARTMENT OF
ELECTRONICS AND COMMUNICATION ENGINEERING
Department of Electronics and Communication Engineering is established in the
year 1997 to meet the requirements of the emerging industry/discipline. The Vision
and the Mission of the department are:

VISION
To create an educational environment for students to excel in their professional carrier, and to
solve the challenges of industry in the field of Electronics and Communication Engineering with
focus on human values, professional ethics and social responsibility.
MISSION
1. Training the students in the core subjects of Electronics and Communication engineering
with due focus on multi-disciplinary areas.

2. Establishing liaison with relevant industries, R&D organizations and renowned


academia for exposure to modern tools and practical aspects of technology.

3. Inculcating team work, leadership, professional ethics, effective communication and


interpersonal skills to make students globally competent in employment as well as
entrepreneurship.

4. Promoting scientific temper and research culture in the graduates towards lifelong
learning, and to work towards the engineering solution in the contexts of society and
environment.

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)

PEO – I. To apply the knowledge of mathematics, science and engineering fundamentals to


find the solution of complex engineering problems concerning societal, health,
safety, cultural and environmental issues.
PEO – II. Empowering graduates to exhibit proficiency in core areas through evolving
technologies in electronics and communication engineering and to identify,
analyze, design, and conduct experiments for innovative solutions.
PEO – III. Facilitating graduates to achieve academic excellence and pursue R&D in multi-
disciplinary domains leading to design of novel products using modern tools and
to promote skills in project management, entrepreneurship and IPR.
PEO- IV. Developing human values, and professional ethics, improving the effective
communication skills, team work, leadership qualities, and life-long learning.
PROGRAM OUTCOMES (POs)

 Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3.   Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4.   Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

5.    Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

6.    The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

7.    Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

8.    Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9.    Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

10.  Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.

11.  Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12.  Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Should be able to gain the in-depth knowledge in core subjects to identify,
formulate, analyze, and suggest viable solutions to the real-life problems in the
field of electronics and communication engineering.

PSO2: Should have the capability to apply modern design tools to analyze and
design subsystems/processes for a variety of applications in the allied fields of
electronics and communications.

PSO3: Should possess good interpersonal skills, and also an ability to work as a
team member as well as team leader with good professional ethics, and also to
become a life-long learner in the context of technological developments.
Department of Electronics & Communication Engineering
Internet of Things and Applications Lab
B. Tech (E.C.E.) III Year II semester

Course Objectives: The objective of this lab is to explore the interconnection and integration of
the physical word and cyber space. Also able to Design and develop IOT devices.

Course Outcomes: After studying this course, the students will be able to
1. Able to understand application areas of IOT
2. Able to understand revolution of internet using Raspberry Pi with python
3. Able to understand building blocks of IOT and characteristic

Mapping of Course Outcomes with Program Outcomes


  PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1   3 3 3 3       2     3  3 3  
CO2   3 3 3 3       2      2 3 3  
CO3   3 3 3 3       2      2 3 3  
 Overall   3 3 3 3       2     3  3 3 3
INTERNET OF THINGS LAB INDEX

Sl. No. Lab Experiment


1 Study and Configure Raspberry Pi 3 (CO2, CO3)
a) Installing Debian OS for Raspberry pi3
b) Flashing and Booting for the Rpi3 for the first time
2 Introduction to Linux Environment – Practice Linux commands and simple python
programs on Rpi3 (CO2)
a) Write a Program for arithmetic operation in Python.
b) Write a Program for looping statement in Python.
c) Programming and Interfacing GPIOS – Blink LED Start/Stop with
Switch
3 Weather monitoring with DHT11 and data storage on cloud (ThingSpeak)
(C01,CO2)
4 Write a program to store senor data in Rpi3 by creating database system.
(C01,CO2)
5 Write a program to send sensor data to Cloud using Node Red service to
perform Data Analytics using Rpi3(C01,CO2)
6 a) Interface and recording pictures and videos using Rpi3
b) Simple program for Colour object detector and tracker(C01,CO2,CO3)
7 Smart Home Application – Security System - Write a program to detect intruder
with proximity sensor, record pictures and send alerts (C01,CO2,CO3)
8 Smart City Application – Street lighting System - Write a program to control street
lights based on the ambience lighting (C01,CO2,CO3)
9 a) Writing python Code to implement of MQTT protocol on Rpi3 –
Publisher (C01,CO2,CO3)
b) Writing python Code to implement of MQTT protocol on Rpi3 –
Subscriber
10 Writing python Code to implement of MQTT protocol on Rpi3 with multiple
Publisher and Subscriber Publisher (C01,CO2,CO3)

IoT Lab Kit Content


 Raspberry Pi 3 model B (Wireless, Bluetooth )
  Micro SD memory card 8 GB
  SD memory card adapter
 DHT 11 Sensor  Resistor,
 LED
 Switch
 Breadboard
 Connecting wires
  HDMI to VGA Cable
  Power Adapter and Micro USB cable
Introduction to Raspberry Pi

The Raspberry Pi is a tiny and affordable computer that you can use to learn programming
through fun, practical project. Raspberry Pi is the name of a series of single-board computers
made by the Raspberry Pi Foundation, a UK charity that aims to educate people in computing
and create easier access to computing education. All over the world, people use the Raspberry Pi
to learn programming skills, build hardware projects, do home automation, implement
Kubernetes clusters and Edge computing, and even use them in industrial applications.

The Raspberry Pi is a very cheap computer that runs Linux, but it also provides a set of GPIO
(general purpose input/output) pins, allowing you to control electronic components for physical
computing and explore the Internet of Things (IoT).

Series and Generations of Raspberry Pi:


The first generation (Raspberry Pi Model B) was released in February 2012, followed by the
simpler and cheaper Model A.

In 2014, the Foundation released a board with an improved design, Raspberry Pi Model B+.
These first generation boards feature ARM11 processors, are approximately credit-card sized and
represent the standard mainline form-factor. Improved A+ and B+ models were released a year
later.[clarification needed] A "Compute Module" was released in April 2014 for embedded
applications.

The Raspberry Pi 2 was released in February 2015 and initially featured a 900 MHz 32-bit quad-
core ARM Cortex-A7 processor with 1 GB RAM. Revision 1.2 featured a 900 MHz 64-bit quad-
core ARM Cortex-A53 processor (the same as that in the Raspberry Pi 3 Model B, but
underclocked to 900 MHz).

Raspberry Pi 3 Model B was released in February 2016 with a 1.2 GHz 64-bit quad core ARM
Cortex-A53 processor, on-board 802.11n Wi-Fi, Bluetooth and USB boot capabilities.
On Pi Day 2018, the Raspberry Pi 3 Model B+ was launched with a faster 1.4 GHz processor, a
three-times faster gigabit Ethernet (throughput limited to ca. 300 Mbit/s by the internal USB 2.0
connection), and 2.4 / 5 GHz dual-band 802.11ac Wi-Fi (100 Mbit/s). Other features are Power
over Ethernet (PoE) (with the add-on PoE HAT), USB boot and network boot (an SD card is no
longer required).

Raspberry Pi 4 Model B was released in June 2019 with a 1.5 GHz 64-bit quad core ARM
Cortex-A72 processor, on-board 802.11ac Wi-Fi, Bluetooth 5, full gigabit Ethernet (throughput
not limited), two USB 2.0 ports, two USB 3.0 ports, 2-8 GB of RAM, and dual-monitor support
via a pair of micro HDMI (HDMI Type D) ports for up to 4K resolution.
Raspberry Pi 400 Kit
Raspberry Pi 400 was released in November 2020. It features a custom board that is derived
from the existing Raspberry Pi 4, specifically remodelled with a keyboard attached. The case was
derived from that of the Raspberry Pi Keyboard. A robust cooling solution (i.e. a broad metal
plate) and an upgraded switched-mode power supply allow the Raspberry Pi 400's Broadcom
BCM2711C0 processor to be clocked at 1.8 GHz, which is slightly higher than the Raspberry Pi
4 it's based on. The keyboard-computer features 4 GB of LPDDR4 RAM.

Raspberry Pi Zero
A Raspberry Pi Zero with smaller size and reduced input/output (I/O) and general-purpose
input/output (GPIO) capabilities was released in November 2015 for US$5.
On 28 February 2017, the Raspberry Pi Zero W was launched, a version of the Zero with Wi-Fi
and Bluetooth capabilities, for US$10.
On 12 January 2018, the Raspberry Pi Zero WH was launched, a version of the Zero W with pre-
soldered GPIO headers.
On 28 October 2021, the Raspberry Pi Zero 2 W was launched, a version of the Zero W with a
system in a package (SiP) designed by Raspberry Pi and based on the Raspberry Pi 3. In contrast
to the older ones, the Pi 2 W is 64 bit capable. The price is around US$15.

Raspberry Pi Pico
Raspberry Pi Pico was released in January 2021 with a retail price of $4. It was Raspberry Pi's
first board based upon a single microcontroller chip; the RP2040, which was designed by
Raspberry Pi in the UK. The Pico has 264 KB of RAM and 2 MB of flash memory. It is
programmable in MicroPython, CircuitPython, C and Rust. It has partnered with Vilros,
Adafruit, Pimoroni, Arduino and SparkFun to build Accessories for Raspberry Pi Pico and
variety of other boards using RP2040 Silicon Platform. Rather than perform the role of general
purpose computer (like the others in the range) it is designed for physical computing, similar in
concept to an Arduino.
Raspberry Pi 3

BCM2837: This is the Broadcom chip used in the Raspberry Pi 3, and in later models of the
Raspberry Pi 2. The underlying architecture of the BCM2837 is identical to the BCM2836. The
only significant difference is the replacement of the ARMv7 quad core cluster with a quad-core
ARM Cortex A53 (ARMv8) cluster.The ARM cores run at 1.2GHz, making the device about
50% faster than the Raspberry Pi 2. The VideocoreIV runs at 400Mhz.
1 Study and Configure Raspberry Pi 3
a) Installing Raspberry Pi OS for Raspberry Pi3
b) Flashing and Booting of the RPi3 for the first time

Raspberry Pi3 basic connections


Its recommend to use an SD card of 16GB or greater capacity with Raspberry Pi OS. If you are
using the lite version of Raspberry Pi OS, you can use a 4GB card.
If you attempt to re-use an SD card you might find the usable capacity is less than you were
expecting. This can be due to partitions previously configured and some “format” utilities can’t
remove them.

Raspberry Pi SD cards will often only appear to have a capacity of 56MB in windows but that is
because it can’t see the much larger Linux partition.

Preparing your SD Card


In order to ensure the SD cards are completely blank and has no partitions that may be hidden
from Windows. To erase it use “SD Formatter” Download and install “SD Formatter” software.

Step 1 – Run

Insert your SD card and run the SDFormatter application :

Note how the card only appears to have a capacity of 56MB despite being a 4GB card.

Double check the drive letter. Then check it again. You do not want to format another device by
accident!
Step 2 – Enable Size Adjustment

As we are specifically interested in restoring the true capacity of the card click “Option” and turn
“Format Size Adjustment” to “ON”.

Click “OK”.
Step 3 – Format

Click “Format” to start the process.

Click “OK” to proceed.

Click “OK” to proceed.

The process should start and it should only take a few seconds.
Step 4 – Finish

When the process finishes it will provide a summary of the cards capacity.

In my example the 4GB card has a capacity of 3.74GB which sounds right. Certainly an
improvement on the 56MB that appeared before.

You can now click “Exit”. Eject your SD card as normal.

Install Raspberry Pi OS using Raspberry Pi Imager


Raspberry Pi Imager (installer GUI) is the quick and easy way to install Raspberry Pi OS and
other operating systems to a microSD card, ready to use with your Raspberry Pi.

Step 1 — Download and Install Raspberry Pi Imager

The first step is to download the Raspberry Pi Imager from the official Raspberry Pi website

(https://www.raspberrypi.com/software/). This tool will allow you to choose an OS, have it

downloaded automatically, and write it to the SD card of your choice.

Do not download files from third-party websites as they may be malicious. Only use trusted

sources.

The imager tool is available on Windows, macOS, and Ubuntu. Images shown will be from a

Mac, but the tool will work the same across the supported platforms.

Raspberry Pi Imager from the Raspberry Pi Foundation

Download the Raspberry Pi Imager for your operating system and follow the installation

instructions and Launch Raspberry Pi Imager


Raspberry Pi Imager

Step 2: Choose OS

Several operating systems are available for selection within the Raspberry Pi Imager, but we will

focus on Raspberry Pi OS.

Select CHOOSE OS

OS Selection within Raspberry Pi Imager


Raspberry Pi OS (32-bit) Lite: This version provides the bare essentials to get you up and

running. There is no Graphical User Interface (GUI) with this image and the size is around 0.4

GB.

Raspberry Pi OS (32-bit): This version includes a GUI and has basic software installed. The size

of this image is around 1.1 GB.

Raspberry Pi OS Full (32-bit): This version includes a GUI and more software installed than the

non-full version. The size of this image is around 2.5 GB.

Select Raspberry Pi OS (32-bit or 64 bit ) here we are going for 32 bit OS

OS Selected in Raspberry Pi Imager

Step 3: Choose SD Card

You’ll now need your SD card connected to your computer to copy over the OS you chose. Select

CHOOSE SD CARD and select the SD card you have connected to your computer.
Select SD Card

You’re now ready to begin writing the OS to your SD card.

OS and SD Card selected

Step 4: Write to SD Card

This step will write the selected OS to the SD card and run a verification that the copy was

successful.
Select WRITE

Write Process Started

The writing process will vary depending on the OS you selected. Typically, this will only take a

few minutes.

Verifying Write
The verify process only takes about a minute to complete.
Write Successful

The OS has now been copied to your SD card. You are now ready to move on to booting your

Raspberry Pi. Select CONTINUE

Manually Installing OS on RPi: using Win32DiskImager (for windows)

Download the Win32DiskImager utility from the Sourceforge Project page as an installer file, and

run it to install the software. Run the Win32DiskImager utility from your desktop or menu.

Manually download the Raspberry Pi OS from official Raspberry Pi website

(https://www.raspberrypi.com/software/operating-systems/ ) and select the OS you want to install

and extract it to get an .img (image file)


Insert the SD card into your SD card reader. You can use the SD card slot if you have one, or an

SD adapter in a USB port. Note the drive letter assigned to the SD card. You can see the drive

letter in the left hand column of Windows Explorer, for example G:

Select the image file you extracted earlier.

In the device box, select the drive letter of the SD card. Be careful to select the correct drive: if

you choose the wrong drive you could destroy the data on your computer’s hard disk! If you are

using an SD card slot in your computer, and can’t see the drive in the Win32DiskImager window,
try using an external SD adapter.

Click 'Write' and wait for the write to complete.

Then Exit the imager and eject the SD card.


1b) Booting Your Raspberry Pi

After installing Raspbian OS in the sd card then insert sd card in raspberry pi and follow below
steps.
Insert your microSDHC card into your Raspberry Pi. Then, hook up your Raspberry Pi to power,
keyboard, mouse, and monitor.

Note: There is a way to configure the Raspberry Pi OS with only power and a network

connection. This is called a headless install

You should be brought directly into the Raspberry Pi OS with a Welcome to RaspberryPi dialog

on the display.

Select Next

Welcome to Raspberry Pi

The next screen will be to set your country.

Choose Your Country

Choose Your Language

Choose Your Timezone

Select the checkboxes if you are using the English language and an English keyboard
Click Next

The next screen will prompt you to change your password. The default username is “pi” and

the default password is “raspberry”.

The next screen will ask you if there is a black border around the desktop. The desktop should

take up the entire screen. If it doesn’t, Raspberry Pi OS can make the adjustment to fill the black

space. This change will take effect when the Raspberry Pi is restarted.

Select the checkbox if the screen shows a black border around the desktop.
Press Next

Set Up Screen

The next screen will prompt you to connect the Raspberry Pi to a wireless network. If no internet

connection is available you can press the skip button to proceed past this step. If you have a wired

connection you will not see this step.

Select a Wireless Network

Press Next
Select Wireless Network

The next screen will prompt you to enter the wireless network password. You can uncheck “hide

characters” to see the characters you are typing.

Enter Wireless Network Password

Press Next

Wireless Network Password


The next screen will ask you if you’d like to have the operating system and applications checked

and updated if necessary. An internet connection is required to complete this step. Press “Skip” if

you’d like to continue without checking.

Note: The time to complete this step will vary based on your internet connection and specs of your

Raspberry Pi.

Press Next

Update Software

A popup will indicate when your system is up to date.

System is up to date
The last screen will let you know that setup is complete and your Raspberry Pi is good to go. Feel

free to restart your Raspberry Pi for any system changes to take effect.

Setup Complete
2 Introduction to Linux Environment – Practice Linux commands and simple
python programs on Rpi3
c) Write a Program for arithmetic operation in Python.
d) Write a Program for looping statement in Python.
b) Programming and Interfacing GPIOS – Blink LED Start/Stop with
Switch

2 c) Unlike in any other programming language, python program for arithmetic operations is
very simple and easy.
Boot Pi Go to main menu Programmingselect Thonny

Program:
num1 = int(input('Enter First number: '))
num2 = int(input('Enter Second number '))
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
#Print output on console
print('Sum of ',num1 ,'and' ,num2 ,'is :',add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',dif)
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',power)
print('Modulus of ',num1 ,'and' ,num2 ,'is :',modulus)

2 d) Python provides us with 2 types of loops as stated below:


 While loop
 For loop

While loop program 1:

number = 5
sum = 0
i=0

while (i<number):
sum = sum + i
i = i+1

print(sum)
While loop program 2:

#Python program to illustrate combining else with while


count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")

for loop program 1 :


for x in range(10):
  print(x)

for loop program 2:

# Python program to illustrate Iterating over a list

print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Loop Control Statements: Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.

Continue Statement: It returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'


for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print 'Current Letter :', letter
var = 10

Break Statement: It brings control out of the loop

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e' or 's'


if letter == 'e' or letter == 's':
break

print 'Current Letter :', letter

Pass Statement: We use pass statement to write empty loops. Pass is also used for empty control
statement, function and classes.

# An empty loop
for letter in 'geeksforgeeks':
pass
print 'Last Letter :', letter

for loop program 3:


for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
2 c) Raspberry Pi Pin Configuration

A powerful feature of the Raspberry Pi is the row of GPIO (general-purpose input/output) pins
along the top edge of the board. A 40-pin GPIO header is found on all current Raspberry Pi
boards. Any of the GPIO pins can be designated (in software) as an input or output pin and used
for a wide range of purposes.
Voltages : Two 5V pins and two 3V3 pins are present on the board, as well as a number of
ground pins (0V), which are unconfigurable. The remaining pins are all general purpose 3V3
pins, meaning outputs are set to 3V3 and inputs are 3V3-tolerant.
Outputs :A GPIO pin designated as an output pin can be set to high (3V3) or low (0V).
Inputs: A GPIO pin designated as an input pin can be read as high (3V3) or low (0V).
The GPIO pins can be used with a variety of alternative functions, some are available on all
pins, others on specific pins like PWM (pulse-width modulation), SPI, I2C,
SerialCommunication.
A handy reference to pinout can be accessed on the Raspberry Pi by opening a terminal window
and running the command pinout.
Pins are numbered/accessed in two ways
The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin
the the plug - i.e the numbers printed on the board (e.g. P1) and in the middle of the diagrams
below.
The GPIO.BCM option means that you are referring to the pins by the "Broadcom SOC
channel" number, these are the numbers after "GPIO" in the green rectangles around the outside
of the below diagram. This is the default mode used by Pi if configuration is not mentioned.

Program to BLINK a LED (Accessing Pins in Board Mode)

########## BLINKING OF LED


import RPi.GPIO as G
import time

G.setmode(G.BOARD)
G.setup(7,G.OUT)
while True:
G.output(7,True)
print("Led is On")
time.sleep(1)
G.output(7,False)
print("Led is off")
time.sleep(1)
PROGRAM TO ON/OFF LED USING PUSH BUTTON (Accessing Pins in BCM Mode)

import RPi.GPIO as GPIO


import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)# connect Button to GPIO23


GPIO.setup(24, GPIO.OUT) # connect LED to GPIO24
try:
while True:
button_state = GPIO.input(23)
if button_state == False:
GPIO.output(24, True)
print('Button Pressed...')
time.sleep(0.2)
else:
GPIO.output(24, False)
except:
GPIO.cleanup()
3 Weather monitoring with DHT11 and data storage on cloud (ThingSpeak)

To install DHT11 sensor library


# 1. To download module from Git, Install Git
# "sudo apt-get install git-core"
#
# 2. Download Adafruit_DHT library
# "git clone https://github.com/adafruit/Adafruit_Python_DHT.git"
#
# 3. Navigate to to Adafruit_Python_DHT directory
# "cd Adafruit_Python_DHT"
#
# 4. For Python2
# "sudo apt-get install build-essential python-dev"
# For Python3
# "sudo apt-get install build-essential python3-dev"
#
# 5. Install DHT Module
# For Python2
# "sudo python setup.py install"
# For Python3
# "sudo python3 setup.py install"

# Sample program to test DHT11


import Adafruit_DHT

try:
while True:
# Read sensor data
humidity, temperature = Adafruit_DHT.read_retry(11,3) # GPIO3 (BCM
notation)
# Print the sensorn data
print ("Humidity = {} %; Temperature = {} C".format(humidity, temperature))

except KeyboardInterrupt:
print "Aborted by user"
Install following in the terminal
sudo pip install thingspeak
sudo pip3 install thingspeak

Program
import thingspeak
import time
import Adafruit_DHT

channel_id = XXXXXX # PUT CHANNEL ID HERE


write_key = 'XXXXXXX' # PUT YOUR WRITE KEY HERE
pin = 3 # BCM Notation
sensor = 11

def measure(channel):
try:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# write
response = channel.update({'field1': temperature, 'field2': humidity})
print ("Humidity = {} %; Temperature = {} C".format(humidity, temperature))

except:
print("connection failed")

if __name__ == "__main__":
channel = thingspeak.Channel(id=channel_id, api_key= write_key)
while True:
measure(channel)
# free account has an api limit of 15sec
time.sleep(15)

https://tutorials-raspberrypi.com/log-raspberry-pi-sensor-data-with-thingspeak-and-analyze-it/
4 CREATING DATA_BASE TO READ SENSOR DATA BY RASPBERRY PI

# CREATING DATA_BASE TO READ SENSOR DATA BY RASPBERRY PI


Install Libraries in the terminal

sudo apt-get install python-pip python-dev libmariadb-dev


sudo apt-get install mariadb-server -y
sudo apt-get install python-mysqldb
sudo pip3 install mysqlclient

sudo mysql
CREATE USER 'student'@'localhost' IDENTIFIED BY 'raspberry'
GRANT ALL PRIVILEGES ON *.* TO 'student'@'localhost';
exit

mysql -u student -p

create database sensor_db;


show databases;
use sensor_db;
create table sensor_values(ID INT PRIMARY KEY AUTO_INCREMENT,Temperature
INT,Humidity INT);
show tables;
insert into sensor_values(Temperature,Humidity) values(20,30);
select * from sensor_values;

################## INSERTING DHT11 Sensor data to the database


Import MySQLdb
Import time
Import Adafruit_DHT
dbConn=
MySQLdb.connect(host=”localhost”,user=”root”,passwd=”raspberry”,db=”sensor_db”)
cursor=dbConn.cursor()
print”Demo program to store sensor data”
time.sleep(1)
print “Inserting data”
time.sleep(1)
try:
while 1:
data=Adafruit_DHT.read_retry(11,3) #11 is DHT11 & 3 is GPIO pin
humidity=int(data[0])
temperature=int(data[1])
print “Temperature”, temperature
print “Humidity”, humidity
cursor.execute(“INSERT INTO
sensor_data(Temperature,Humidity)VALUES(%s %s)”),
(str(temperature),str(humidity))
dbConn.commit()
print
time.sleep(2)
except keyboardInterrupt:
print “Aborted by user”
5 Write a program to send sensor data to Cloud using Node Red service to
perform Data Analytics using Rpi3

Node-RED is a visual tool for wiring the Internet of Things developed by IBM Emerging
Technology and the open source community. Node RED is installed in Raspbian operating
system by default.

Start up your Raspberry Pi. Click on the Raspberry icon, then the Programming menu to open
Node-RED.

You should see a window displaying information about Node-RED starting up.
Now go to the Internet menu and open Chromium Web Browser.

In Chromium, locate the address bar at the top and type in localhost:1880, then press Enter. This
will display the Node-RED interface. (Your Raspberry Pi does not need to be connected to the
internet to use Node-RED: localhost is the address the Raspberry Pi uses to refer to itself
and :1880 means that it is looking at port 1880.)
Connecting to a GPIO pin

Programs in Node-RED are called flows. You can see that your blank page is labelled as Flow
1 in the tab at the top. You can create as many flows as you want and they can all run at the same
time. For this guide, we will only need one flow.
o The coloured blocks on the left side of the interface are the nodes. Scroll right down to
the bottom of the list and you will see some nodes labelled Raspberry Pi.

You will see two nodes with the label rpi gpio: these are the ones we will use to talk to the GPIO
pins on the Raspberry Pi. The first one in the list, with the raspberry icon on the left, is for inputs.
Using a button push to control something would be an example of an input. The second node,
with the raspberry icon on the right, is for outputs. Switching on an LED would be an example of
an output. Drag an output node onto the blank page in the middle.
Double-click on the node and a box will appear to let you configure the node. Change the GPIO
pin to be GPIO17 and tick Initialise pin state?. Leave the setting for Initial level of pin on low.
Give the node a name - we called it Green LED because the LED we used was green, but if
yours is a different colour feel free to change the name. When you are finished, click Done.

Injecting messages

o Now scroll back up to the list of nodes. To turn the LED on and off, we need an input. In
Node-RED we can inject messages into the flow and cause things to happen as a result.
Drag an inject node onto the flow.

o Double-click on the inject node. Use the drop down next to Payload to change the data
type to string and type 1 in the Payload box - this will be the message. Type On in
the Name box. Press Done.
o Repeat the previous steps to create another inject node, except this time add 0 as the
payload message, and call this node Off.

o Now look for the grey dot on the right side of the inject nodes. Click and drag from the
grey dot on the On node to the grey dot on your LED node to join them up. Repeat for
the Off node, also joining it to the LED node.
Deploying the flow
o Our flow is finished, so we can deploy it. Click on the big red Deploy button on the top
right of the screen. A message should pop up at the top saying “Successfully deployed”.
This is similar to pressing the green flag in Scratch or F5 to run your code in Python.

o Now click on the blue square on the left of the On node to inject the message 1.
The Green LED node receives the message and your LED should light up. You should be
able to turn the LED off by clicking the blue square on the Off node, which injects the
message 0.

https://projects.raspberrypi.org/en/projects/getting-started-with-node-red/7
6 a) Interface and recording pictures and videos using Rpi3
b) Simple program for Colour object detector and tracker

Connect the Camera Module


With the Raspberry pi switched off, lift up the tab of the camera port from the two edges of the
port. The camera module strip has one side covered with the blue cover at the bottom. Insert the
camera module strip in to the camera port with the blue side of the camera module strip facing
the Ethernet port and then lift down the tab.

Enabling the Camera


To enable the camera, open the Raspberry pi configuration tool from the main menu.

From the interfaces tab, make sure that the camera is enabled. After enabling, reboot your
Raspberry pi.
Taking a Picture in terminal
To capture the picture, type the following command in the terminal.
1. raspistill -o pic.jpg
This will capture the image after 5 seconds. You will also see a preview while capturing the
picture or video  if you are using an external or any other device connected through the HDMI
cable. If you are controlling your Raspberry pi through the Remote connection, then you will not
see the preview window.
If you want to capture the picture after some specific time, then use the following command.
Enter the time in milliseconds after ‘-t’.
1. raspistill -t 10000 -o pic1.jpg
If you just want the preview. Then use the below command
1. raspistill -p –o

Recording a video with Raspberry pi camera module


To record a video, type the following command in the terminal. It will record a video of 5
seconds. The video will be saved in the ‘.h264’ format.
1. raspivid -o video.h264
Python code to capture the image
To Install library for the camera module.

sudo apt-get install python-picamera

Program:
from time import sleep
from picamera import PiCamera
camera = PiCamera()
camera.resolution = (1024, 768)
camera.start_preview()
# To capture a picture
sleep(2)# Camera warm-up time
camera.capture('picture1.jpg')
camera.stop_preview()

# Take a picture including the annotation


camera.annotate_text = 'Hello world!'
#camera.start_preview()
sleep(2)# Camera warm-up time
camera.capture('picture2.jpg')

#Capture and crop the picture


#camera.start_preview()
sleep(2)# Camera warm-up time
camera.capture('picture3.jpg', resize=(320, 240))
#camera.stop_preview()

#Recording Video using Pi Camera


camera.resolution = (640, 480)
camera.start_recording('my_video.h264')
camera.wait_recording(10) #record for 10 seconds
camera.stop_recording()

7 Smart Home Application – Security System - Write a program to detect intruder


with proximity sensor, record pictures and send alerts

PIR PROGRAM:

import RPi.GPIO as GPIO


import time
from picamera import PiCamera
GPIO.setmode(GPIO.BOARD) #Set GPIO to pin numbering
pir = 8 #Assign pin 8 to PIR
led = 10 #Assign pin 10 to LED
GPIO.setup(pir, GPIO.IN) #Setup GPIO pin PIR as input
GPIO.setup(led, GPIO.OUT) #Setup GPIO pin for LED as output
print ("Sensor initializing . . .")
time.sleep(2) #Give sensor time to startup
print ("Active")
print ("Press Ctrl+c to end program")
camera = PiCamera()
camera.resolution = (1024, 768)

try:
while True:

if GPIO.input(pir) == True: #If PIR pin goes high, motion is detected


print ("Motion Detected!")
GPIO.output(led, True)#Turn on LED for sometime
camera.start_preview()
camera.annotate_text = 'Intruder !!'
time.sleep(2)
camera.capture('foo1.jpg', resize=(320, 240))
camera.start_preview()
time.sleep(4) #Keep LED on for 4 seconds
GPIO.output(led, False) #Turn off LED
time.sleep(2)
except KeyboardInterrupt: #Ctrl+c
pass #Do nothing, continue to finally
finally:
GPIO.output(led, False) #Turn off LED in case left on
GPIO.cleanup() #reset all GPIO
print ("Program ended")
8 Smart City Application – Street lighting System - Write a program to control street
lights based on the ambience lighting

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BOARD) #Set GPIO to pin numbering
ldr = 8 #Assign pin 8 to PIR
led = 10 #Assign pin 10 to LED
GPIO.setup(ldr, GPIO.IN) #Setup GPIO pin ldr as input
GPIO.setup(led, GPIO.OUT) #Setup GPIO pin for LED as output
print ("Press Ctrl+c to end program")
try:
while True:

while GPIO.input(ldr) == True: #If ldr pin goes high


print ("Night")
print("street light on ")
GPIO.output(led, True)#Turn on LED
time.sleep(2)
else: #If ldr pin goes low
print ("Day")
print("street light off ")
GPIO.output(led, False) #Turn on LED
time.sleep(2)

except KeyboardInterrupt: #Ctrl+c


pass #Do nothing, continue to finally
finally:
GPIO.output(led, False) #Turn off LED in case left on
GPIO.cleanup() #reset all GPIO
print ("Program ended")
Analog-to-Digital Converter chip is the best way to read analog voltages from the Pi. However,
there's a way to read many sensors without an ADC! By measuring the sensor as a resistor that is
used to 'fill up' a capacitor, we can count how long it takes. It's not nearly as precise as an ADC
and its a little flakey (since it depends on the Pi timing itself which can vary based on how 'busy'
the computer is)

The way we do this is by taking advantage of a basic electronic property of resistors and
capacitors. It turns out that if you take a capacitor that is initially storing no voltage, and then
connect it to power (like 3.3V) through a resistor, it will charge up to the power voltage slowly.
The bigger the resistor, the slower it is.

This technique only works with sensors that act like resistors. however, there are quite a few fun
sensors that act this way: photocells, thermistors (temperature sensors), flex sensors, force-
sensitive resistors, and many more.

It cannot be used with sensors that have a pure analog output like IR distance sensors or analog
accelerometers.

This capture from an oscilloscope shows whats happening on the digital pin (yellow). The blue
line indicates when the Pi starts counting and when the counting is complete, about 4.5ms later.

This is because the capacitor acts like a bucket and the resistor is like a thin pipe. To fill a bucket
up with a very thin pipe takes enough time that you can figure out how wide the pipe is by timing
how long it takes to fill the bucket up halfway

In this case, our 'bucket' is a 1uF ceramic capacitor. You can change the capacitor nearly any
way you want but the timing values will also change. 1uF seems to be an OK place to start for
most sensors. If you want more range, use a bigger cap - but it will take longer to measure. For
faster reads, go with a smaller capacitor.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)

#define the pin that goes to the circuit


pin_to_circuit = 7
def rc_time (pin_to_circuit):
count = 0

#Output on the pin for


GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)

#Change the pin back to input


GPIO.setup(pin_to_circuit, GPIO.IN)

#Count until the pin goes high


while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1

return count

#Catch when script is interrupted, cleanup correctly


try:
# Main loop
while True:
print(rc_time(pin_to_circuit))
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
9 a) Writing python Code to implement of MQTT protocol on Rpi3 –
Publisher
b) Writing python Code to implement of MQTT protocol on Rpi3 –
Subscriber

Raspberry Pi MQTT Server – Install and test Mosquitto


There are several applications that can be used to send and receive through MQTT, but the
simplest on the Raspberry Pi is probably Mosquitto. We will install this on the Raspberry Pi first:
sudo apt-get install -y mosquitto mosquitto-clients

After installation, a Mosquitto server is started automatically. We open a subscriber in the


channel “test_channel” waiting for messages:
mosquitto_sub -h localhost -v -t test_channel

The channel is here like a frequency, on which one hears. For example, different data may be
sent in different channels (e.g., temperature, humidity, brightness, etc.).
In order to simply transfer data, we can either use the same Raspberry Pi (open new terminal /
SSH connection) or send the data from another Pi. If we use the same Raspberry Pi, use is easily
possible. For this we simply send a test message (as publisher) in the same channel:
mosquitto_pub -h localhost -t test_channel -m "Hello Raspberry Pi"

Otherwise you have to specify the internal IP address (eg 192.168.1.5) of the recipient instead of
“localhost”. On the receiver side, the message should appear soforn.
 
Raspberry Pi MQTT data exchange with Python
The communication is super easy, as we have seen. In order for us to be able to use the whole
thing from scripts, we want to make it available to Python. For this purpose, we first install a
library via the Python package manager (for Python3 also use pip3):
sudo pip3 install paho-mqtt

Alternatively (for example, if the package could not be properly installed) you can also install it
manually:
git clone https://github.com/eclipse/paho.mqtt.python.git
cd paho.mqtt.python
python setup.py install

 
We start with the subscriber’s Python code

1 import paho.mqtt.client as mqtt


2  
3 MQTT_SERVER = "localhost"
4 MQTT_PATH = "test_channel"
5  
6 # The callback for when the client receives a CONNACK response from the server.
7 def on_connect(client, userdata, flags, rc):
8     print("Connected with result code "+str(rc))
9  
10     # Subscribing in on_connect() means that if we lose the connection and
11     # reconnect then subscriptions will be renewed.
12     client.subscribe(MQTT_PATH)
13  
14 # The callback for when a PUBLISH message is received from the server.
15 def on_message(client, userdata, msg):
16     print(msg.topic+" "+str(msg.payload))
17     # more callbacks, etc
18  
19 client = mqtt.Client()
20 client.on_connect = on_connect
21 client.on_message = on_message
22  
23 client.connect(MQTT_SERVER, 1883, 60)
24  
25 # Blocking call that processes network traffic, dispatches callbacks and
26 # handles reconnecting.
27 # Other loop*() functions are available that give a threaded interface and a
28 # manual interface.
29 client.loop_forever()

Either you send a message as usual by Shell Command, or we also create a Python Sender /
Publisher.

The publisher’s code looks like this (create a new file and then run it, keeping in mind the correct
IP address):
Python Publisher
1 import paho.mqtt.publish as publish
2  
3 MQTT_SERVER = "192.168.1.5" # or ''localhost''
4 MQTT_PATH = "test_channel"
5  
publish.single(MQTT_PATH, "Hello World!", hostname=MQTT_SERVER)
 
10 Writing python Code to implement of MQTT protocol on Rpi3 with multiple
Publisher and Subscriber

Install python MQTT Client


# "sudo pip install paho-mqtt"
https://io.adafruit.com/
# ---------------------------
#
# MQTT_BROKER : io.adafruit.com
# MQTT_PORT : 1883
# MQTT_USER_NAME : your Adafruit account username (see "accounts.adafruit.com
page")
# MQTT_USER_PASSWORD : your Adafruit IO key (click the AIO Key button on a
dashboard to find the key)
# PUB_TOPIC1 : <username>/feeds/<feed name>
# SUB_TOPIC1 : <username>/feeds/<feed name>

Code
# Import MQTT Module
import paho.mqtt.client as mqtt
# Import Sensor Module
import Adafruit_DHT
# Import Time Module
import time

while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 27) # 11:DHT11, 22:DHT22;
#GPIO27 (BCM notation)
print(temperature, humidity)
# Create a MQTT instance
client=mqtt.Client()
# Connect to MQTT Broker
client.username_pw_set("<Adafruit_User_Name","<Adafruit_Token>")#replace with
your user name and password
client.connect("io.adafruit.com",1883)
# Publish data to "IoT_Demo/feeds/temperature" topic
client.publish("IoT_Demo/feeds/temperature",temperature)
# Publish data for every 5 seconds
time.sleep(5)

You might also like