0% found this document useful (0 votes)
0 views

unit-4_iot

This document outlines the development of various IoT applications, including an intrusion detection system, temperature monitoring system, remote control of LEDs, smarter parking system, and livestock tracking system. Each application involves specific hardware and software requirements, circuit designs, and code implementations using Arduino and other technologies. The document provides step-by-step instructions for building circuits, writing code, and integrating components to achieve real-time data processing and notifications.

Uploaded by

psingh80437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

unit-4_iot

This document outlines the development of various IoT applications, including an intrusion detection system, temperature monitoring system, remote control of LEDs, smarter parking system, and livestock tracking system. Each application involves specific hardware and software requirements, circuit designs, and code implementations using Arduino and other technologies. The document provides step-by-step instructions for building circuits, writing code, and integrating components to achieve real-time data processing and notifications.

Uploaded by

psingh80437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

IoT Patterns: Realtime Clients

In this chapter, you are going to build an example


of this pattern, an intrusion detection system
.The first component is an Arduino device that
has a motion sensor attached to it. The second
component is an MQTT broker. You will use the
publish-subscribe model of MQTT for sending
intrusion detection notifications in Realtime. The
final component of your IoT application is an
Android app that subscribes to the MQTT broker
and shows an alert notification to users
whenever Arduino detects an intrusion and
publishes a message to the MQTT broker.

Components of the intrusion detection system


Learning Objectives

• Read motion sensor data from Arduino


• Publish sensor data to an MQTT broker
• Build an Android app that subscribes to
an MQTT broker
• Display a notification in the app
whenever a new message is
• published to the MQTT broker
Hardware Required
Hardware required for the intrusion detection system

Software Required
In order to develop the intrusion detection system, you need
the following software :
• Arduino IDE 1.6.4 or later version
• Android Studio 1.5.1 or later
In this section, you are going to build the circuit required for the intrusion
detection system. This circuit uses an HC-SR501 motion sensor to detect
intrusions.
1. Make sure your Arduino is not connected to a power source, such as to a
computer via a USB or a battery.
2. Attach a WiFi shield to the top of Arduino. All the pins should align.
Circuit 3. Use jumper cables to connect the power (5V) and ground (GND) ports on
Arduino to the power (+) and ground (-) ports on the breadboard.
4. Now that your breadboard has a power source, use jumper cables to connect
the power (+) and ground (-) ports of your breadboard to the power and ground
ports of the motion sensor.
5. To read motion sensor values, you need to connect a jumper cable from signal
port of the motion sensor (usually the middle port) to digital port 3 of your
Arduino. You can use other digital ports as well, but if you do, make sure to
change the Arduino code appropriately.
Circuit
Code (Arduino)

Start your Arduino IDE and type the code


provided here or download it from book’s
site and open it. All the code goes into a
single source file (*.ino ), but in order to
make it easy to understand and reuse, it has
been divided into five sections.
• External libraries
• Internet connectivity (WiFi)
• Read sensor data
• MQTT (publish)
• Standard functions
External Libraries
• #include <SPI.h>
• #include <WiFi.h>
• #include <PubSubClient.h>
Read Sensor Data
calibrateSensor()
readSensorData()
Data Publish using MQTT
publishSensorData()
Code for Standard Arduino Function—setup()
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Connect Arduino to internet

Standard connectToInternet();
// Calibrate motion sensor

Functions calibrateSensor();
}
Code for Standard Arduino Function—loop()
void loop()
{
//Read sensor data
readSensorData();
}
Code
(Android)
• Display a notification in real-
time whenever motion is
detected by the sensor.
• Create a simple screen where
app users can see when last
motionwas detected.
Create new project from the Android Studio menu bar
New project configuration
Android device selection screen
Activity template selection screen
Activity customization screen
app > manifests > AndroidManifest.xml

app > java > *.* - package-hierarchy

app > res > layout > *.xml


Web Apps
• Read data from a
temperature sensor
Learning
Objectives • Publish sensor data to a
server

• Display sensor data in a


web-based dashboard
Hardware
Required
In order to develop the temperature monitoring
Software system, you need the following software:
Required • Arduino IDE 1.6.4 or later
• PHP server (installed or hosted)
• MySQL server (installed or hosted)
• Text editor
In this section, you are going to build the circuit required for the
temperature monitoring

system. This circuit uses a low-cost and easy-to-use TMP36


temperature sensor. The sensor returns its values in voltage, which is
converted into Celsius and Fahrenheit.
Circuit 1. Make sure Arduino is not connected to a power source, such as to
a computer via USB or a battery.

2. Attach a WiFi shield to the top of the Arduino. All the pins should
align.

3. Use jumper cables to connect the power (5V) and ground(GND)


ports on Arduino to the power (+) and ground (-) ports on the
breadboard.
4. Now that your breadboard has a power source,
use jumper cables to connect the power (+) and
ground (-) ports of your breadboard to the power
and ground ports of the temperature sensor. The
left pin of the sensor is the power (+) and the right
pin is the ground (-).
5. To read values from the temperature sensor, you
will need to connect a jumper cable from the analog
voltage port (middle pin) of the temperature sensor
to the A0 (Analog) port of Arduino. Your code will
read the voltage from this port to calculate the
temperature in Celsius and Fahrenheit.
Actual circuit
of the
temperature
monitoring
system
Database Table (MySQL)

• CREATE TABLE `TEMPERATURE_MONITORING_DATA`

TEMPERATURE_MONITORING_DATA table structure


Code (PHP) & Database Connection

Common database connectivity file called util-dbconn.php


$servername = "SERVER_NAME";
$dbname = "DB_NAME";
$username = "DB_USERNAME";
$password = "DB_PASSWORD";

File to receive and store data in add.php

The file for analytics dashboard is index.php


Code (Arduino)
The final component of this project is the Arduino code for connecting to the Internet using WiFi,
reading data from the temperature sensor, and publishing it to a server. Start your Arduino IDE and
either type the code provided here or download it from book’s site and open it. All the code goes
into a single source file ( *.ino ), but in order to make it easy to understand and reuse, it has been
divided into five sections.

• External libraries

• Internet connectivity (WiFi)

• Read sensor data

• HTTP (publish)

• Standard functions
Code for Including External Dependencies
• #include <SPI.h>
• #include <WiFi.h>
int TEMP_SENSOR_PIN = A0;
//Read Temperature Sensor Value
int temperatureSensorValue = analogRead(TEMP_SENSOR_PIN);
Code for Standard Arduino Functions
void setup()
{
// Initialize serial port
Serial.begin(9600);
//Connect Arduino to internet
connectToInternet();
}
void loop()
{
// Read sensor data
readSensorData();
// Transmit sensor data
transmitSensorData();
// Delay
delay(6000);
}
Log messages from the temperature monitoring system

Dashboard of the temperature monitoring system


IoT Patterns: Remote Control
Learning Objectives

• Write code to turn LEDs connected to Arduino


on or off
• Subscribe Arduino to an MQTT broker
• Build an Android app that publishes to an MQTT
broker
Hardware
Required
Software Required

ARDUINO IDE 1.6.4 OR ANDROID STUDIO 1.5.1


LATER OR LATER
Circuit

1.Make sure your Arduino is not connected to a power source, such as to a computer via a USB or a
battery.
2.Attach a WiFi shield to the top of the Arduino. All the pins should align.
3. Unlike previous circuits, you do not want to power your breadboard all the time, instead you
want to control it. So use a jumper cable to connect digital port 3 of your Arduino to power (+) port
on the breadboard. You will use this port to turn the LED on and off.
4. Use jumper cables to connect the ground (GND) port on Arduino to the ground (-) port on the
breadboard.
5 Attach an LED to your breadboard.
6. Use the jumper cable to connect the power (+) port of the breadboard to the power (+) port of
the LED.
7. Attach a 220Ω resistor between the ground (-) port of the breadboard and the ground (-) port of
the LED.
Code
(Android)
External libraries

Internet connectivity (WiFi)

Code MQTT (subscribe)


(Arduino)
Control LED

Standard functions
#include <SPI.h>

External #include <WiFi.h>

Libraries
#include <PubSubClient.h>
Control Lights
int ledPin = 3;
void turnLightsOnOff()
{
// Check if lights are currently on or off
if(digitalRead(ledPin) == LOW)
{
//Turn lights on
Serial.println("[INFO] Turning lights on");
digitalWrite(ledPin, HIGH);
}
else
{
// Turn lights off
Serial.println("[INFO] Turning lights off");
digitalWrite(ledPin, LOW);
}
}
Standard Functions

void setup()
{
// Initialize serial port
Serial.begin(9600);
// Connect Arduino to internet
connectToInternet();
void loop()
{
// Wait for messages from MQTT broker
pubSubClient.loop();
}
The Final
Product
IoT Patterns:On-Demand Clients

Components of the smarter parking system

Learning Objectives
At the end of this chapter, you will be able to:

• Read data from a proximity sensor

• Send sensor data to a server using HTTP

• Display sensor data in an iOS app using HTTP

Software Required
In order to develop the smarter parking system, you need the following software:

• Arduino IDE 1.6.4 or later

• PHP server (installed or hosted)


• MySQL server (installed or hosted)

• Text editor

• Xcode
Hardware Required

Circuit
In this section, you are going to build the circuit required for the smarter parking system. This
circuit uses an ultrasonic proximity sensor to detect objects. The sensor sends an ultrasonic
burst, which reflects from objects in front of it. The circuit reads the echo that is used to
calculate the distance to nearest object.
1. Make sure Arduino is not connected to a power source, such as to a computer via a USB or
a battery.

2. Attach a WiFi shield to the top of the Arduino. All the pins should align.

3. Use jumper cables to connect the power (5V) and ground (GND) ports on Arduino to the
power (+) and ground (-) ports on the breadboard.

4. Now that your breadboard has a power source, use jumper cables to connect the power (+)
and ground (-) ports of your breadboard to the power and ground ports of the proximity
sensor.
5. To trigger an ultrasonic burst, connect a jumper cable from the TRIG pin of the sensor to
the digital port 2 of Arduino. Your code will set the value of this port to LOW, HIGH, and

LOW in order to trigger the burst.

6. To read the echo, connect a jumper cable from the ECHO pin of the sensor to the digital port
3 of Arduino. Your code will read values from this port to calculate distance of the object.
Database Table (MySQL)
Create and Initialize Table SQL

CREATE TABLE `PARKING_SPOTS_DATA` (

`PARKING_SPOTS_COUNT` int(11) NOT NULL,

`TIMESTAMP` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP

Code (PHP)

Receive and Store Sensor Data


Get the Parking Spot Count

Code (Arduino)
The second component of this project is the Arduino code. This code connects Arduinoto the
Internet using WiFi, checks if parking spot is open or not, and publishes this information to a
server.

Start your Arduino IDE and either type the code provided or download it from book’s site and
open it. All the code goes into a single source file ( *.ino ), but in order to make it easy to
understand and reuse, it has been divided into five sections.

• External libraries

• Internet connectivity (WiFi)

• Read sensor data

• HTTP (publish)
• Standard functions

External Libraries
The first section of code, as provided in Listing 7-5 , includes all external libraries required

to run the code. Since you are connecting to the Internet wirelessly, the main dependency

of the code is on <WiFi.h> .

Code for Including External Dependencies

#include <SPI.h>
#include <WiFi.h>
Standard Functions
The fifth and final code section is shown in Listing 7-8 . It implements Arduino’s standard
setup() and loop() functions. The setup() function initializes the serial port, sets the pin modes
for the trigger and echo pins, connects to the Internet, and calibrates the proximity sensor. The
loop() function needs to call readSensorData() at regular intervals as it internally calls the
publishSensorData() function.

void setup()

// Initialize serial port

Serial.begin(9600);
// Set pin mode

pinMode(ECHOPIN, INPUT);

pinMode(TRIGPIN, OUTPUT);

// Connect Arduino to internet

connectToInternet();

// Calibrate sensor

calibrateSensor();
}

void loop()

// Read sensor data

readSensorData();

delay(5000);

}
IoT Patterns: Location Aware

Location-aware devices are going to be one of the largest contributors of savings from an IoT
implementation. The IoT pattern is seen in various types of scenarios, including optimal route
planning, endangered wildlife tracking, and pinpointing crash locations. In this chapter, you
are going to build a livestock tracking system . The first component is an Arduino device that
captures the current coordinates and publishes them to a server using an HTTP request. The
second component is a server that receives GPS coordinates and stores them in a database. The
final component is a web page that shows stored GPS coordinates on a map. This web page
resides on the server as well.

The components of livestock tracking system

Learning Objectives
At the end of this chapter, you will be able to:

• Read GPS coordinates

• Publish GPS coordinates to a server

• Display GPS coordinates in a map

Hardware Required
Hardware required for the livestock tracking system

Software Required
In order to develop this livestock tracking system, you need the following software:

• Arduino IDE 1.6.4 or later

• PHP server (installed or hosted)


• MySQL server (installed or hosted)

• Text editor

Circuit
In this section, you are going to build the circuit required for the livestock tracking system.

This circuit uses the NEO6MV2 GPS module for getting current latitude and longitude data.
The GPS module has a positional accuracy of 5 meters.

1. Make sure Arduino is not connected to a power source, such as to a computer via USB or a
battery.
2. Attach a WiFi shield to the top of the Arduino. All the pins should align.

3. Use jumper cables to connect the power (3.3V) and ground (GND) ports on Arduino to the
power (+) and ground (-) ports on the breadboard.

4. Now that your breadboard has a power source, use jumper cables to connect the power (+)
and ground (-) ports of your breadboard to the power and ground ports of the GPS.

5. To read the GPS data, you will need to connect a jumper cable from the RX (Receive) port
of the GPS to Digital Port 3 of Arduino. Your code will use data from this port to find the
latitude and longitude information.

6. Similar to Step 5, you also need to connect a jumper cable from the TX (Transmit) port of
the GPS to Digital Port 2 of Arduino. Your code will use data from this port to find the latitude
and longitude information.
Database Table (MySQL)
As discussed in the previous two chapters, before you can send HTTP requests from Arduino,
you need to build a service that will receive the data. The livestock tracking system will be
displaying the latest GPS coordinates on a map, so you need to create a database table that will
store those GPS coordinates.

CREATE TABLE `GPS_TRACKER_DATA`

GPS_TRACKER_DATA table structure


Code (PHP)

Common database connectivity file called util-dbconn.php

Receive and Store Sensor Data

File to receive and add/update data in update.php

Code (Arduino)
The final component of this project is the Arduino code for connecting to the Internet using
WiFi, getting the current GPS coordinates, and publishing them to a server.Start your Arduino
IDE and either type the code provided here or download it from the site and open it. All the
code goes into a single source file ( *.ino ), but in order to make it easy to understand and reuse,
it has been divided into five sections.
• External libraries

• Internet connectivity (WiFi)


• Read GPS coordinates
• HTTP (publish)

• Standard functions

External Libraries
#include <SPI.h>

#include <WiFi.h>
#include <TinyGPS.h>

#include <SoftwareSerial.h>

Data Publish
// Make a HTTP request:
client.println("GET /gpstracker/update.php?" + requestData +" HTTP/1.1");
Standard Functions
void setup()

// Initialize serial port

Serial.begin(115200);

// Initialize serial port for GPS data

ss.begin(9600);

//Connect Arduino to internet


connectToInternet();

}
void loop()

// Get GPS Coordinates

getGPSCoordinates();

}
IoT Patterns: Machine to Human

Learning Objectives
At the end of this chapter, you will be able to:

• Read data from a proximity sensor

• Publish message to an MQTT broker

• Build a workflow in Effektif (renamed to Signavio Workflow)


• Create a Node-RED flow and initiate it from Arduino

Hardware Required
Software Required
In order to develop this waste management system, you need the following software :

• Arduino IDE 1.6.4 or later

• Effektif (hosted)

• Node-RED 0.13.2 or later

Circuit
In this section, you are going to build the circuit required for the waste management system.
This circuit uses an ultrasonic proximity sensor to detect objects, as illustrated in Chapter 7 .
The sensor is attached to the top of a garbage can and sends an ultrasonic burst that reflects off
of the garbage in the can. The circuit reads the echo, which is used to calculate the level of
garbage .
1. Make sure Arduino is not connected to a power source, such as to a computer via a USB or
a battery.

2. Attach a WiFi shield to the top of the Arduino. All the pins should align.

3. Use jumper cables to connect the power (5V) and ground (GND) ports on Arduino to the
power (+) and ground (-) ports on the breadboard.

4. Now that your breadboard has a power source, use jumper cables to connect the power (+)
and ground (-) ports of your breadboard to the power and ground ports of the proximity sensor.

5. To trigger an ultrasonic burst, connect a jumper cable from the TRIG pin of the sensor to
Digital Port 2 of Arduino. Your code will set the value of this port to LOW, HIGH, and then
LOW in order to trigger the burst.

6. To read the echo, connect a jumper cable from the ECHO pin of the sensor to Digital Port 3
of Arduino. Your code will read the values from this port to calculate the level of garbage in
the can.
Code (Arduino)
Next you are going to write the code for the first component of this application. This code will
connect Arduino to the Internet using WiFi, read the proximity sensor data to get garbage levels,
and publish that information to an MQTT broker. Start your Arduino IDE and type the code
provided here or download it from the site and open it. All the code goes into a single source
file ( *.ino ), but in order to make it easy to understand and reuse, it has been divided into five
sections.

• External libraries

• Internet connectivity (WiFi)

• Read sensor data

• MQTT (publish)
• Standard functions

External Libraries
The first section of code, as provided in Listing 10-1 , includes all the external libraries

required to run the code. This sketch has two main dependencies—for Internet

connectivity, you need to include <WiFi.h> (assuming you are using a WiFi shield) and

for MQTT broker communication, you need to include <PubSubClient.h> .

Code for Including External Dependencies

#include <SPI.h>
#include <WiFi.h>

#include <PubSubClient.h>

Standard Functions
The final code section is shown in Listing 10-4 . It implements Arduino’s standard setup()

and loop() functions.

The setup() function initializes the serial port, sets the pin modes for the trigger and echo pins,
connects to the Internet, and calibrates the proximity sensor.

The loop() function simply needs to call readSensorData() at regular intervals.

Listing 10-4. Code for Standard Arduino Functions

void setup()

{
// Initialize serial port
Serial.begin(9600);

// Set pin mode

pinMode(ECHOPIN, INPUT);

pinMode(TRIGPIN, OUTPUT);
// Connect Arduino to internet

connectToInternet();

// Calibrate sensor

calibrateSensor();

Effektif Workflow
Effektif is a cloud-based platform that lets you automate routine workflows and processes into
applications within minutes. For the purposes of this project, you can sign up for their free 30-
day trial membership. You are going to define a very simple single step workflow that allows
a person to enter a garbage pickup schedule.

Process Creation

Process Configurations

• Trigger: Select how the process can be started


• Actions: Specify what human and system actions will happen in the process and their
orders
• Details: Choose who will be involved in the process
• Versions: View a list of all versions of processes published till date
Node-RED Flow
The Final Product
IoT Patterns: Machine to Machine
As IoT technology evolves and machines become smarter and more capable, the need for
human intervention will reduce. Machines will be able to autonomously respond to alerts
generated by other machines. In this chapter, you are going to build an energy conservation
system that will show how two machines can communicate. The first component is an Arduino
device that monitors light brightness levels and sends an alert whenever the levels are low. The
second component is an MQTT broker that helps avoid point-to-point communication.
Multiple devices can communicate with each other without knowing each other’sidentities.

Learning Objectives
At the end of this chapter, you will be able to:
• Read data from a light sensor
• Publish messages to an MQTT broker
• Control LEDs
• Subscribe Arduino to an MQTT broker

Light Sensor Device


The first component of your IoT application is an Arduino device that will monitor the
light brightness levels and publish a message when they are low.

Code (Arduino)
Next you are going to write code for connecting Arduino to the Internet using WiFi, reading
light sensor data, and publishing it to an MQTT broker.
Start your Arduino IDE and type the code provided here or download it from the site and
open it. All the code goes into a single source file ( *.ino ), but in order to make it easy to
understand and reuse, it has been divided into five sections:
• External libraries
• Internet connectivity (WiFi)
• Read sensor data
• MQTT (publish)
• Standard functions
External Libraries
The first section of the code, as provided in Listing 11-1 , includes all the external libraries
required to run the code. This sketch has two main dependencies—for Internet connectivity
you need to include <WiFi.h> (assuming you are using a WiFi shield), and for MQTT broker
communication, you need to include <PubSubClient.h> .
Listing 11-1. Code for Including External Dependencies
#include <SPI.h>
#include <WiFi.h>
#include <PubSubClient.h>

Read Sensor Data


int lightValue;
void readSensorData()
{
//Read Light Sensor Value
lightValue = analogRead(A0);
Serial.print("[INFO] Light Sensor Reading: ");
Serial.println(lightValue);
if(lightValue < 500)
{
publishSensorData("LOW");
}
else
{
publishSensorData("HIGH");
}
Serial.println("-----------------------------------------------");
}
Standard Functions
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Connect Arduino to internet
connectToInternet();
}
void loop()
{
// Read sensor data
readSensorData();
// Delay
delay(5000);
}
Lighting Control Device
Code (Arduino)
Next you are going to write code for connecting Arduino to the Internet using WiFi,
subscribing to an MQTT broker, and controlling the attached LED . Start your Arduino IDE
and type the code provided here or download it from the site and open it. All the code goes into
a single source file ( *.ino ), but in order to make it easy to understand and reuse, it has been
divided into five sections:
• External libraries
• Internet connectivity (WiFi)
• MQTT (subscribe)
• Control LED
• Standard functions
External Libraries
The first section of code, as provided in Listing 11-5 , includes all the external libraries
required to run the code. This sketch has two main dependencies—for Internet
connectivity you need to include <WiFi.h> (assuming you are using a WiFi shield) and for
the MQTT broker communication, you need to include <PubSubClient.h> .

#include <SPI.h>
#include <WiFi.h>
#include <PubSubClient.h>
Control Lights
The fourth section of code, as provided in Listing 11-7 , defines the variables, constants, and
functions that are going to be used for controlling the LED.
This code switches the state of the LED based on the value of the action parameter.
Listing 11-7. Code for Controlling the LED
int ledPin = 3;
void turnLightsOnOff(String action)
{
// Check if lights are currently on or off
if(action == "ON")
{
//Turn lights on
Serial.println("[INFO] Turning lights on");
digitalWrite(ledPin, HIGH);
}
else
{
// Turn lights off
Serial.println("[INFO] Turning lights off");
digitalWrite(ledPin, LOW);
}
}
Standard Functions
The final code section is provided in Listing 11-8 . It implements Arduino’s standard setup()
and loop() functions.The setup() function initializes the serial port, connects to the internet, and
subscribes to the MQTT topic.The MQTT broker has already been initialized and subscribed,
so in loop()function, you only need to wait for new messages from the MQTT broker.
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Connect Arduino to internet
connectToInternet();
// Set LED pin mode
pinMode(ledPin, OUTPUT);
//Connect MQTT Broker
Serial.println("[INFO] Connecting to MQTT Broker");
if (pubSubClient.connect("arduinoClient"))
{
Serial.println("[INFO] Connection to MQTT Broker Successful");
pubSubClient.subscribe(topic);
}
else
{
Serial.println("[INFO] Connection to MQTT Broker Failed");
}
}
void loop()
{
// Wait for messages from MQTT broker
pubSubClient.loop();
}
The Final Product
Log messages from the light sensor device

Log messages from the lighting control device

You might also like