Professional Documents
Culture Documents
IoT Lab With Rpi3 Lab Manual1
IoT Lab With Rpi3 Lab Manual1
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.
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.
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.
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.
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.
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.
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
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).
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 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.
Step 1 – Run
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
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.
The first step is to download the Raspberry Pi Imager from the official Raspberry Pi website
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.
Download the Raspberry Pi Imager for your operating system and follow the installation
Step 2: Choose OS
Several operating systems are available for selection within the Raspberry Pi Imager, but we will
Select CHOOSE OS
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
Raspberry Pi OS Full (32-bit): This version includes a GUI and more software installed than the
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
This step will write the selected OS to the SD card and run a verification that the copy was
successful.
Select WRITE
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
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.
SD adapter in a USB port. Note the drive letter assigned to the SD card. You can see the drive
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.
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
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
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 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
Press Next
Select Wireless Network
The next screen will prompt you to enter the wireless network password. You can uncheck “hide
Press Next
and updated if necessary. An internet connection is required to complete this step. Press “Skip” if
Note: The time to complete this step will vary based on your internet connection and specs of your
Raspberry Pi.
Press Next
Update Software
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 Programmingselect 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)
number = 5
sum = 0
i=0
while (i<number):
sum = sum + i
i = i+1
print(sum)
While loop program 2:
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
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
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.
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)
GPIO.setmode(GPIO.BCM)
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
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
sudo mysql
CREATE USER 'student'@'localhost' IDENTIFIED BY 'raspberry'
GRANT ALL PRIVILEGES ON *.* TO 'student'@'localhost';
exit
mysql -u student -p
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
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
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()
PIR PROGRAM:
try:
while True:
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)
return count
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
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
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)