H - IoT Practicals
H - IoT Practicals
Practical:1
a) Introduction to – Arduino, Arduino components and IDE .
What is Arduino?
Arduino is an open-source electronics platform based on easy-to-use hardware and software.
Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message
- and turn it into an output - activating a motor, turning on an LED, publishing something online.
You can tell your board what to do by sending a set of instructions to the microcontroller on the
board.
Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed
at students without a background in electronics and programming. As soon as it reached a wider
community, the Arduino board started changing to adapt to new needs and challenges,
differentiating its offer from simple 8-bit boards to products for IoT applications, wearable, 3D
printing, and embedded environments.
Breadboard:
Arduino PINS:
Vin: This is the input voltage pin of the Arduino board used to provide input supply from an external
power
source.
5V: This pin of the Arduino board is used as a regulated power supply voltage and it is used to give
supply to
the board as well as onboard components.
3.3V: This pin of the board is used to provide a supply of 3.3V which is generated from a voltage
regulator on the board
GND: This pin of the board is used to ground the Arduino board.
Reset: This pin of the board is used to reset the microcontroller. It is used to Resets the
microcontroller.
Analog Pins: The pins A0 to A5 are used as an analog input and it is in the range of 0-5V.
Digital Pins: The pins 0 to 13 are used as a digital input or output for the Arduino board.
Serial Pins: These pins are also known as a UART pin. It is used for communication between the
Arduino board and a computer or other devices. The transmitter pin number 1 and receiver pin
number 0 are used to transmit and receive the data resp.
External Interrupt Pins: This pin of the Arduino board is used to produce the External interrupt
and it is done by pin numbers 2 and 3.
PWM Pins: This pin of the board is used to convert the digital signal into an analog by varying thewidth
of the Pulse. The pin numbers 3,5,6,9,10 and 11 are used as a PWM pin.
SPI Pins: This is the Serial Peripheral Interface pin, it is used to maintain SPI communication with
the help of the SPI library. SPI pins include:
1. SS: Pin number 10 is used as a Slave Select
2. MOSI: Pin number 11 is used as a Master Out Slave In
3. MISO: Pin number 12 is used as a Master In Slave Out
4. SCK: Pin number 13 is used as a Serial Clock
LED Pin: The board has an inbuilt LED using digital pin-13. The LED glows only when the digital
pin becomes
high.
AREF Pin: This is an analog reference pin of the Arduino board. It is used to provide a reference
voltage from an external power supply.
What is Arduino IDE?
The Arduino integrated development environment (IDE) is a cross-platform application (for
Microsoft Windows, macOS, and Linux) that is written in the Java programming language. It
originated from the IDE for the languages Processing and Wiring. It includes a code editor with
features such as text cutting and pasting, searching and replacing text, automatic indenting, brace
matching, and syntax highlighting, and provides simple oneclick mechanisms to compile and upload
programs to an Arduino board. It also contains a message area, a text console, a toolbar with buttons
for common functions and a hierarchy of operation menus. The source code for the IDE is released
under the GNU General Public License, version 2. The Arduino IDE supports the languages C and
C++ using special rules of code structuring. The Arduino IDE supplies a software library from the
Wiring project, which provides many common input and output procedures.
Source Code:-
Practical:2
AIM: - Perform Experiment using Arduino UNO for LED ON-OFF with
PUSH button and dimming of LED using loop.
Component: -
• Arduino
• Breadboard
• LED
• Register
• Jumper wire
• Push button
Source code:-
Output:-
Thinkercad circuit:
Circuit:
Practical:3
AIM: - Perform Experiment using Arduino for traffic light simulator.
Component: -
• Arduino
• Breadboard
• LED
• Register
• Jumper wire
Source code: -
Output: -
Thinkercad circuit
Circuit:
Practical:4
AIM: - Perform Experiment using Arduino for multicolored LED stream with buzzer
Component: -
• Arduino
• Multicolored LED
• Register
• Jumper wire
Source code: -
void setup(){
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(9, OUTPUT);
} void loop(){
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000); }
Circuit: -
Practical:5
AIM:- To study different types of sensors and their application.
1. Ultrasonicnic sensor
• An ultrasonic sensor is an instrument
that measures the distance to an object
using ultrasonic sound waves.
• When it doesn’t work When waves are not reflected back towards the sensor.
2. Gas sensor
3. Color sensor
• These sensors are photoelectric devices that can emit light and detect the color of reflected light
from an object.
• The ratio of the intensity of light determines the amount of light reflected and absorbed by the
object.
4. PIR sensor
• A motion sensor is a sensor that detects moving things, such as people. These types of motion
sensors are on top of a door to
detect weather a person has
walked inside or not.4
• A Passive infrared sensor(PIR) is an electronic sensor that measures infrared(IR) light radiating
from objects in its field of view.
• This type of motion sensor is only the receptor of infrared waves and does not release any infrared
beam like that is done in Active Infrared Sensors.
5. IR sensor
• Infrared sensor is an electronic device that emits light in order to sense some object of the
surroundings.
7. Rain sensor
• This sensor works on the bending strip principle which means whenever the strip is twisted then
its resistance will be changed.
This can be measured with the
help of any controller.
• It includes a printed circuit board (control board) that “collects” the raindrops. As raindrops are
collected on the circuit board, they create paths of parallel resistance that are measured via the op-
amp. The lower the resistance (or the more water), the lower the voltage output.
• The module includes a rain board and a control board that is separate for more convenience. It has
a power indicator LED and an adjustable sensitivity through a potentiometer. The module is based
on the LM393 op-amp.
• These sensors normally used to check volumetric water content, and another group of sensors
calculates a new property of moisture within soils named water potential.
9. Hall sensor
• A Hall Effect sensor is a transducer that varies its output voltage in response to a magnetic field.
• Hall effect sensors are used for
proximity switching, positioning,
speed detection, and current
sensing.
• In its simplest form, the sensor
operates as an analog transducer,
directly returning a voltage.
• With a known magnetic field, its
distance from the Hall plate can
be determined. Using groups of
sensors, the relative position of the magnet can be deduced.
• Frequently, a Hall sensor is combined with circuitry that allows the device to act in a digital
(on/off) mode, and may be called a switch in this configuration.
Practical:6
AIM: - Perform Experiment using Arduino UNO to keep Buzzer/LED ON/OFF
based on the moment of the object in the range of PIR Motion sensor
Component: -
• Arduino
• LED
• Register
• Jumper wire
• PIR motion sensor
Source code: -
void setup()
{ pinMode(led, OUTPUT); // initalize LED as an output
pinMode(sensor, INPUT); // initialize sensor as an input
Serial.begin(9600); // initialize serial
}
void loop()
{ val = digitalRead(sensor); // read sensor value
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(led, HIGH); // turn LED ON
delay(500); // delay 100 milliseconds
if (state == LOW) {
Serial.println("Motion detected!");
state = HIGH; // update variable state to HIGH }}
else {
digitalWrite(led, LOW); // turn LED OFF delay(500); // delay 200 milliseconds
if (state == HIGH){
Serial.println("Motion stopped!");
state = LOW; // update variable state to LOW
}}}
Circuit: -
Practical:7
AIM: - Perform Experiment using Arduino UNO to keep Buzzer/LED ON/OFF based
on the moment of the object with Ultrasonic sensor
Component: -
• Arduino
• LED
• Jumper wire
• Ultrasonic sensor
Source code: -
// constants won't change const int TRIG_PIN = 6;
// Arduino pin connected to Ultrasonic Sensor's TRIG pin const int ECHO_PIN = 7;
// Arduino pin connected to Ultrasonic Sensor's ECHO pin const int LED_PIN = 13;
// Arduino pin connected to LED's pin const int DISTANCE_THRESHOLD = 10;
// centimeters
// variables will change:
float duration_us, distance_cm;
void setup() {
Serial.begin (9600); // initialize serial port
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode pinMode(ECHO_PIN,
INPUT); // set arduino pin to input mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
}
void loop() {
// generate a 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance
distance_cm = 0.017 * duration_us;
if(distance_cm < DISTANCE_THRESHOLD)
digitalWrite(LED_PIN, HIGH); // turn on LED
else
digitalWrite(LED_PIN, LOW); // turn off LED
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
Output:-
Thinkercad circuit:
Circuit:-
Practical:8
AIM:- Perform an Experiment using Arduino UNO to detect Rain.
Component:-
https://circuitdigest.com/microcontroller-projects/interfacing-rain-sensor-with-arduino
• Arduino
• LED
• Jumper wire
• Rain detect sensor
Source code:-
// Sensor pins pin D6 LED output, pin A0 analog Input
#define ledPin 13
#define sensorPin A0
void setup() {
Serial.begin(9600);
pinMode(ledPin,
OUTPUT);
digitalWrite(ledPin,
LOW); }
void loop() {
Serial.print("Analog output: ");
Serial.println(readSensor());
delay(500); }
int readSensor() {
int sensorValue = analogRead(sensorPin); // Read the analog value from sensor
int outputValue = map(sensorValue, 0, 1023, 255, 0); // map the 10-bit data to 8-bit data
if(outputValue>185) {
digitalWrite(ledPin,outputValue);
delay(10); }
else {
digitalWrite(ledPin,LOW);
delay(10); }
return outputValue; // Return analog moisture value
}
Output:-
Circuit:-
sensor.Output:
Program:
Practical:10
Aim: Using NodeMCU with Arduino
IDE.Output:
• This tutorial is all about Humidity & Temperature Monitoring using DHT11 &
NodeMCU on ThingSpeak. It explains how to log Humidity & Temperature data on the
cloud. We can use Thingspeak as a cloud service provider and DHT11 to measure
temperature and humidity.
• This tutorial is for NodeMCU on Arduino IDE. You can also configure the ESP8266-
12E board with Arduino to monitor temperature and humidity.
Components:
4. Go to Tools > Board > ESP8266 Boards (3.0.2) and Select NodeMCU 1.0
Now, after adding NodeMCU Board in Arduino, we have to install certain libraries to
connect Wi-Fi to NodeMCU and upload data on ThingSpeak cloud service. For that follow
steps givenbelow:
2. Open ArduinoIDE
3. Go to Sketch > Include Library > Add .ZIP Library and install all four libraries
4. After installing you will be able to see those libraries in Include Library option
3. Add channel and Field name. Then Scroll down and save the channel.
*Do not modify any other options
4. After channel is created, Go to API Keys and copy and paste this key toa separate notepad file.
You will need it later while programming.
Steps:
1. Make connection as shown below in circuit diagram
7. If you don’t get any errors, compile the code and upload it to NodeMCU board.
Code:
#include <ArduinoWiFiServer.h>
#include <BearSSLHelpers.h>
#include <CertStoreBearSSL.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiGratuitous.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include
<WiFiClientSecureBearSSL.h> #include
<WiFiServer.h>
#include <WiFiServerSecure.h>
#include
<WiFiServerSecureBearSSL.h> #include
<WiFiUdp.h>
#include <Adafruit_Sensor.h>
// Robo India Tutorial
// Simple code upload the tempeature and humidity data using thingspeak.com
// Hardware: NodeMCU,DHT11
#include <DHT.h> // Including library for dht
String apiKey = "PASTE API KEY HERE"; // Enter your Write API key from
ThingSpeak const char *ssid = "WIFI NAME"; // replace with your wifi ssid and
wpa2 key const char *pass = "WIFI
PASSWORD"; const char* server =
"api.thingspeak.com";
#define DHTPIN 0 //pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient
client; void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void
loop(){
float h = dht.readHumidity(); float t =
dht.readTemperatu
re(); if (isnan(h) ||
isnan(t)){
Serial.println("Failed to read from DHT sensor!"); return;}
if (client.connect(server,80)) // "184.106.153.149" or
api.thingspeak.com{ String postStr = apiKey;
postStr +="&field1="; postStr += String(t); postStr +="&field2=";
postStr +=
String(h); postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type:application/x-www-form-
urlencoded\n"); client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n"); client.print(postStr);
Serial.print("Temperature: "); Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
// thingspeak needs minimum 15 sec delay between updates, i've set it to 30
seconds delay(1000);
You will be needing an image writer to write the downloaded OS into the SD card (micro SD
card in case of R aspberry Pi B+ model). So download the "win32 disk imager" from
the website.
2. Writing the image
Insert the SD card into the laptop/pc and run the image writer. Once open, browse and select
the downloaded Raspbian image file. Select the correct device, that is the drive
Representing the SD card. If the drive (or device) selected is different from the SD card
then the other selected drive will become corrupted. SO be careful.
After that, click on the "Write" button in the bottom. As an example, see the image
below,where the SD card (or micro SD) drive is represented by the letter "G:\"
Fig. 2 OS Installation
Once the write is complete, eject the SD card and insert it into the Raspberry Pi andturn it
on. It should start booting up.
3. Setting up the Pi
Please remember that after booting the Pi, there might be situations when the user credentials
like the "username" and password will be asked. Raspberry Pi comes with a default user name and
password and so always use it whenever it is being asked. The credentials are:
login: pi
password: raspberry
When the Pi has been booted for the first time, a screen called the “Setup
configuration”
If you have missed the "Setup Options" screen, its not a problem, you can always get it by the
following command in the terminal.
sudo raspi -config
Once you execute this command the "Setup Options" screen will come up as shown in the
Image above
Now that the Setup Options window is up, we will have to set a few things. After completing each of
the steps below, if it asks to reboot the Pi, please do so. After the reboot, if you don't get the "Setup
Options" screen, then follow the command given above to get the screen/window.
• The first thing to do: select the first option in the list of the setup options window, that
is select the "Expand
Filesystem " option and hit the enter key. We do this to make use of all the space present
on the SD card as a full partition. All this does is, expand the OS to fit the whole space
on the SD card which can then be used as the storage memory for the Pi
• The second thing to do:
Select the third option in the list of the setup options window, that is select the "Enable
Boot To Desktop/Scratch" option and hit the enter key. It will take you to another
window called the "choose boot option" window that looks like the image below.
In the "choose boot option window", select the second option, that is, "Desktop Log in asuser'pi'
at the graphical desktop" and hit the enter button. Once done you will be taken back tothe " Setup
Options" page, if not select the "OK" button at the bottom of this window and you will betaken back
to the previous window. We do this because we want to boot into the desktop environment which we
are familiar with. If we don't do this step then the Raspberry Pi boots into aterminal each time with
no GUI options. Once, both the steps are done, select the "finish"b utton atthe bottom of the page and
it should reboot automatically. If it doesn't, then
use the following command in the terminal to reboot.
sudo reboot
Once you are on the desktop, open a terminal and enter the following command to update
the firmware of the Pi.
sudo rpi-update
5. Conclusion
So, we have covered the steps to get the Pi up and running. This method works on all the different
models of Raspberry Pi (model A, B, B+ and also RPi 2) as Raspbain was made to be supported on all
models. However, while installing other software or libraries, the
procedure might change a bit while installing depending on the model of the Pi or the version of
Raspbian itself. The concept of Rasberry is to keep trying till you get the result or build that you want.
This might involve a lot of trial and error but spending the time will be worth it. The actual usage
doesn't end here. This is just the beginning. It is up to you to go ahead to build somet hing amazing out
of it.
GPIO:
Act as both digital output and digital input. Output: turn a GPIO pin high or low.
Input: detect a GPIO pin high or low
Power Pins
The header provides 5V on Pin 2 and 3.3V on Pin 1. The 3.3V supply is limited to 50mA. The 5V
supply draws current directly from your microUSB supply so can use whatever is left over after the
board has taken its share. A 1A power supply could supply up to 300mA once the Board has drawn
700mA.
Basic GPIO
The header provides 17 Pins that can be configured as inputs and outputs. By default they are all
configured as inputs except GPIO 14 & 15.
In order to use these pins you must tell the system whether they are inputs or outputs. This can be
achieved a number of ways and it depends on how you intend to control them. I intend on using Python.
SDA & SCL: The 'DA' in SDA stands for data, the 'CL' in SCL stands for clock; the S stands for serial.
You can do more reading about the significance of the clock line for various types of computer bus,
You will probably find I2C devices that come with their own userspace drivers and the linux kernel
includes some as well. Most computers have an I2C bus, presumably for some of the purposes listed
by wikipedia, such as interfacing with the RTC (real time clock) and configuring memory. However,
it is not exposed, meaning you can't attach anything else to it, and there are a lot of interesting things
that could be attached -- pretty much any kind of common sensor (barometers, accelerometers,
gyroscopes, luminometers, etc.) as well as output devices and displays. You can buy a USB to I2C
adapter for a normal computer, but they cost a few hundred dollars. You can attach multiple devices to
the exposed bus on the pi.
UART, TXD & RXD: This is a traditional serial line; for decades most computers have had a port
for this and a port for parallel.1 Some pi oriented OS distros such as Raspbian by default boot with
this serial line active as a console, and you can plug the other end into another computer and use
some appropriate software to communicate with it. Note this interface does not have a clock line; the
two pins may be used for full duplex communication (simultaneous
Practical:12
Aim:-CONNECT THE LED TO THE RASPBERRY PI
Components:
● Raspberry Pi
● One LED
● One 330 Ohm resistor
● Jumper wires
● Breadboard
The 330 Ohm resistor is a current limiting resistor. Current limiting resistors should always be used
when connecting LEDs to the GPIO pins. If an LED is connected to a GPIO pin without a resistor, the
LED will draw too much current, which can damage the Raspberry Pi or burn out the LED. Here is
a nice calculator that will give you the value of a current limiting resistor to use for different
LEDs. After connecting the hardware components, the next step is to create a Python program to
switch on and off the LED. This program will make the LED turn on and off once every second and
output the status of the LED to the terminal. The first step is to create a Python file. To do this, open
the Raspberry Pi terminal and type nano LED.py. Then press Enter. This will create a file named
LED.py and open it in the Nano text editor. Copy and paste the Python code below into Nano and
save and closethe file.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sudo python
LED.py
You should see the LED blinking on and off once every second.
You should also see a message in the terminal with “LED is ON“ when the LED is turned on,
and “LED is OFF” when the LED is turned off.
Humans and other animals emit radiation all the time. This is nothing to be concerned about, though, as the
type of radiation we emit is infrared radiation (IR), which is pretty harmless at the levels at which it is
emitted by humans. In fact, all objects at temperatures above absolute zero (-
273.15C) emit infrared radiation. A PIR sensor detects changes in the amount of infrared
radiation it receives. When there is a significant change in the amount of infrared radiation it detects, then
a pulse is triggered. This means that a PIR sensor can detect when a human (or any animal) moves in front
of it. The pulse emitted when a PIR detects motion needs to be amplified, and so it needs to be powered.
There are three pins on the PIR: they should be
labelled Vcc, Gnd, and Out. These labels are sometimes concealed beneath the Fresnel lens (the white cap),
which you can temporarily remove to see the pin labels.
As shown above, the Vcc pin needs to be attached to a 5V pin on the Raspberry Pi.
The Gnd pin on the PIR sensor can be attached to any ground pin on the Raspberry Pi.
Lastly, the Out pin needs to be connected to any of the GPIO pins.
Tuning a PIR
Most PIR sensors have two potentiometers on them. These can control the sensitivity of the
sensors, and also the period of time for which the PIR will signal when motion is detecte
Program:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN) try:
print “PIR Module Test (CTRL+C to exit)”
time.sleep(2) print “Ready” while True:
if GPIO.input(PIR_PIN):
print “Motion Detected!”
time.sleep(1)
except KeyboardInterrupt:
print “ Quit”
GPIO.cleanup()
Practical:13
AIM:-13.1 Perform Experiment using Arduino UNO to detect Soil
Component:-
● Arduino
● LED
● Jumper wire
Source code:-
// C++ code //
int moisture_data = 0; void setup()
{
pinMode(A0, INPUT); Serial.begin(9600);
pinMode(12, OUTPUT);
}
void loop()
{
moisture_data = analogRead(A0);
Serial.println(moisture_data);
if (moisture_data < 21) {
digitalWrite(12, HIGH);
} else
{ digitalWrite(12, LOW);
} delay(10); // Delay a little bit to improve simulation performance }
Thinkercad Circuit:-
Circuit:-
Practical 13 (13.2)
AIM:- Case Study on IOT Pet Trackers
Customers:-
A new service allowing pet owners to monitor their pets’ locations with the help of wearable trackers
managed via a mobile app.
Challenge:-
The Customer wanted a big data solution that would allow the users to be always up-to-date about
their pets’ locations, receive real-time notifications about critical events, as well as access the reports
on their pet’s presence.
The solution was to enable media content transfer (audio, video and photos) so that pet owners could
speak to their pets or see where their pets were at a particular moment.
As the Customer expected that the number of users would be constantly growing, the solution was to
be easily scalable to store and process an increasing amount of data.
Solution:-
Results:-
The Customer received an easily scalable big data solution that allows processing 30,000+ events
per second from 1 million devices. As a result, the users can track their pet’s location in real time,
as well as send and receive photos, videos and voice messages. If a critical event happens (e.g., a
pet crossed a geo fence set by the pet owner or the pet’s wearable tracker turned “out of
communication,” etc.), the user receives push-notifications. Pet owners can also access hourly,
weekly or monthly reports set automatically, or manually tune the reporting period, if needed.
Technologies and Tools:-
Amazon Web Services, MQTT, Apache Kafka (stream data processor), Apache Spark (data
aggregator), MongoDB (data warehouse), PostgreSQL RDS (operational database), RESTful
web services.