IoT unit 4

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

DEPARTMENT OF COMPUTER SCIENCE & ENGG.

BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)


B. Tech 8 Sem Subject: Internet of Things
Interoperability in the Internet of Things (IoT) refers to the ability of diverse devices, systems,
and applica ons to connect, communicate, and exchange data seamlessly and effec vely. It
allows different components of the IoT ecosystem to work together, regardless of their
manufacturer, opera ng system, or communica on protocols. Interoperability is crucial for
maximizing the poten al of IoT deployments and enabling the crea on of integrated solu ons
that can deliver value across various domains.
Characteris cs of Interoperability in IoT:
1. Communica on Protocols: Interoperability requires the adop on of standardized
communica on protocols that enable devices to exchange data reliably. Common
protocols include MQTT, CoAP, HTTP, and WebSockets, among others.
2. Data Formats and Standards: Standardizing data formats and protocols ensures that
devices can understand and interpret the data they receive. Common standards
include JSON, XML, and MessagePack.
3. Device Compa bility: Interoperability ensures that devices from different
manufacturers can interact seamlessly, even if they use different hardware pla orms
or so ware implementa ons.
4. APIs and Middleware: Applica on Programming Interfaces (APIs) and middleware play
a crucial role in facilita ng interoperability by providing standardized interfaces for
communica on and data exchange between devices and applica ons.
5. Seman c Interoperability: This aspect ensures that devices and systems can
understand the meaning of the data they exchange, enabling more intelligent and
context‐aware interac ons.
6. Security and Privacy: Interoperability must be balanced with security and privacy
considera ons to protect sensi ve data and ensure secure communica on between
devices and systems.
Benefits of Interoperability in IoT:
1. Scalability: Interoperability allows IoT ecosystems to scale more effec vely by
integra ng new devices and services without requiring significant changes to exis ng
infrastructure.
2. Flexibility: Interoperable systems offer greater flexibility, allowing organiza ons to
choose best‐of‐breed solu ons from mul ple vendors and adapt to evolving
requirements.
3. Innova on: By enabling collabora on and integra on across diverse pla orms and
technologies, interoperability fosters innova on and accelerates the development of
new IoT applica ons and services.
4. Improved Efficiency: Interoperable systems can streamline processes, automate tasks,
and improve data exchange, leading to increased opera onal efficiency and
produc vity.
5. Enhanced User Experience: Seamless interoperability enhances the overall user
experience by enabling smoother interac ons between devices and applica ons,
reducing complexity, and improving reliability.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
NodeMCU
NodeMCU is an open‐source firmware and development kit that helps in building Internet of Things
(IoT) applica ons. It is based on the ESP8266 Wi‐Fi module, which is a low‐cost, low‐power, and highly
integrated Wi‐Fi chip.

ESP8266 Wi‐Fi Module:

1. The ESP8266 is a versa le Wi‐Fi module developed by Espressif Systems. It features a


microcontroller unit (MCU) and Wi‐Fi connec vity, making it ideal for IoT applica ons.
2. The ESP8266 module is capable of connec ng to Wi‐Fi networks, making TCP/IP connec ons,
and hos ng a small web server.
3. It supports both sta on (client) and access point (AP) modes, allowing it to connect to exis ng
Wi‐Fi networks or act as a Wi‐Fi access point.

NodeMCU Development Kit:

1. NodeMCU is a development kit based on the ESP8266 module. It includes a microcontroller


unit (MCU), flash memory, and USB‐to‐serial converter.
2. The NodeMCU development board provides easy access to the GPIO pins of the ESP8266
module, allowing for easy interfacing with sensors, actuators, and other electronic
components.
3. NodeMCU boards are typically programmed using the Arduino IDE or Lua scrip ng language.

Features of NodeMCU:

1. Easy Prototyping: NodeMCU simplifies the development of IoT projects by providing an easy‐
to‐use pla orm for prototyping and experimenta on.
2. Built‐in Wi‐Fi: NodeMCU boards come with built‐in Wi‐Fi connec vity, allowing them to
connect to local Wi‐Fi networks and communicate with other devices over the internet.
3. GPIO Pins: NodeMCU boards feature several General‐Purpose Input/Output (GPIO) pins that
can be used to interface with sensors, actuators, displays, and other peripherals.
4. Arduino IDE Compa bility: NodeMCU boards can be programmed using the Arduino IDE,
making it easy to leverage exis ng libraries and code examples for Arduino‐based projects.
5. Lua Scrip ng Support: NodeMCU also supports Lua scrip ng language, allowing for rapid
development of IoT applica ons using high‐level scrip ng.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
Applica ons of NodeMCU:

1. Home Automa on: NodeMCU can be used to build smart home automa on systems for
controlling lights, appliances, and security devices.
2. Environmental Monitoring: NodeMCU can be used to monitor environmental parameters such
as temperature, humidity, and air quality using sensors.
3. Industrial IoT: NodeMCU can be deployed in industrial se ngs for monitoring and controlling
machinery, equipment, and processes.
4. IoT Prototyping: NodeMCU is widely used for prototyping IoT projects, including data logging,
remote sensing, and remote‐control applica ons.

GPIO Pins (General‐Purpose Input/Output):

 NodeMCU boards typically feature mul ple GPIO pins that can be configured as either digital
input or output pins.
 These pins can be used to read digital signals from sensors or control digital actuators such as
LEDs, relays, and motors.
 GPIO pins can also support features such as PWM (Pulse Width Modula on) for controlling
the intensity of LEDs or servos.

Analog Pins:

 Some NodeMCU boards include a few analog input pins that can be used to read analog
voltage levels from sensors.
 Analog pins convert con nuous analog voltage into discrete digital values using an analog‐to‐
digital converter (ADC).
 Analog pins are o en used to interface with sensors that provide analog outputs, such as
temperature sensors, light sensors, and poten ometers.

Power Pins: Power pins provide electrical power to the NodeMCU board and connected components.
The main power pins include:

 Vin (Voltage Input): Used to supply external power to the NodeMCU board.
 3.3V (3.3 Volts): Provides regulated 3.3‐volt power output for low‐power components.
 GND (Ground): Provides a reference voltage for electrical circuits and serves as a common
ground connec on.

USB Interface:

 The USB interface allows users to connect the NodeMCU board to a computer for
programming, communica on, and power supply.
 It is used to upload firmware (programs) to the NodeMCU board, as well as for serial
communica on between the board and the computer.
 The USB interface also provides power to the NodeMCU board when connected to a computer
via a USB cable.

Reset Bu on:

 Similar to Arduino boards, NodeMCU boards may include a reset bu on that allows users to
restart the board and reset the microcontroller.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
 Pressing the reset bu on momentarily causes the microcontroller to reset, restar ng the
execu on of the firmware uploaded to the board.

Voltage Regulator:
• NodeMCU boards typically include a voltage regulator that regulates the input voltage
to a stable voltage level required by the microcontroller and other components.
• The voltage regulator ensures that the NodeMCU board operates reliably within its
specified voltage range, even when powered by external power sources.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
Arduino
Arduino is an open‐source electronics pla orm based on easy‐to‐use hardware and so ware.
It consists of a physical programmable circuit board (o en referred to as a microcontroller)
and a development environment for wri ng so ware to program the board.

Hardware:
1. Arduino boards come in various shapes and sizes, but they typically include a microcontroller
unit (MCU), digital and analog input/output pins (GPIO), USB interface for programming and
communica on, and power supply op ons.
2. The microcontroller on Arduino boards is usually an Atmel AVR or ARM‐based processor. The
most commonly used microcontroller is the Atmega series, such as the Atmega328P.

So ware:
1. The Arduino So ware (IDE) is a cross‐pla orm Integrated Development Environment that is
used to write and upload code to Arduino boards. It is based on the Processing programming
environment and the Wiring framework.
2. The Arduino IDE supports C and C++ programming languages. Users write code in a simplified
version of C/C++ called the Arduino programming language.
3. The IDE includes a code editor, compiler, and uploader tool, making it easy to write, compile,
and upload code to Arduino boards.

Programming Language:
1. Arduino programming language is based on Wiring, which is a simplified version of C/C++ with
addi onal libraries and func ons specific to Arduino.
2. The language includes func ons for ini alizing pins, reading analog and digital inputs,
controlling outputs, and communica ng with other devices via serial communica on, I2C, SPI,
etc.

Applica ons: Arduino is widely used in various applica ons, including:


1. Robo cs and automa on

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
2. Home automa on and IoT projects
3. Wearable electronics
4. Educa onal projects and STEM educa on
5. Art installa ons and interac ve exhibits
6. Prototyping and product development

Digital Pins (GPIO):

 Digital pins are used for general‐purpose input and output (GPIO) opera ons.
 They can be configured as either inputs or outputs, allowing users to read digital signals from
sensors or control digital actuators such as LEDs, relays, and motors.
 Digital pins typically support binary logic (high/low or on/off) and are represented by the
digitalWrite() and digitalRead() func ons in the Arduino programming language.

Analog Pins:

 Analog pins are used to read analog voltage levels from sensors.
 They convert the con nuous analog voltage into a discrete digital value using an analog‐to‐
digital converter (ADC).
 Analog pins are o en used to interface with sensors that provide analog outputs, such as
temperature sensors, light sensors, and poten ometers.
 Analog pins are represented by the analogRead() func on in the Arduino programming
language, which returns a value between 0 and 1023 corresponding to the input voltage level.

Power Pins: Power pins provide electrical power to the Arduino board and connected components.
The main power pins include:

 Vin (Voltage Input): Used to supply external power to the Arduino board.
 5V (5 Volts): Provides regulated 5‐volt power output for external components.
 3.3V (3.3 Volts): Provides regulated 3.3‐volt power output for low‐power components.
 GND (Ground): Provides a reference voltage for electrical circuits and serves as a common
ground connec on.

Reset Bu on:

 The reset bu on is used to restart the Arduino board and reset the microcontroller.
 Pressing the reset bu on momentarily causes the microcontroller to reset, restar ng the
execu on of the program uploaded to the board.

USB Interface:

 The USB interface allows users to connect the Arduino board to a computer for programming,
communica on, and power supply.
 It is used to upload sketches (programs) to the Arduino board, as well as for serial
communica on between the board and the computer.
 The USB interface also provides power to the Arduino board when connected to a computer
via a USB cable.

Voltage Regulator:

 Arduino boards typically include a voltage regulator that regulates the input voltage to a stable
voltage level required by the microcontroller and other components.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
 The voltage regulator ensures that the Arduino board operates reliably within its specified
voltage range, even when powered by external power sources.

Crystal Oscillator (Clock):

 Many Arduino boards include a crystal oscillator that generates a precise clock signal used by
the microcontroller for ming and synchroniza on purposes.
 The crystal oscillator ensures accurate ming of opera ons performed by the microcontroller,
such as execu ng instruc ons and genera ng output signals.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
Raspberry Pi
Raspberry Pi is a series of small single‐board computers developed by the Raspberry Pi Founda on in
the United Kingdom. It is designed to promote computer science educa on and facilitate
experimenta on with hardware and so ware projects.

Hardware:

1. Raspberry Pi boards are small, affordable, and credit‐card‐sized computers that feature a
microprocessor, memory, input/output (I/O) ports, and other components integrated onto a
single printed circuit board (PCB).
2. The Raspberry Pi Founda on releases different models of Raspberry Pi boards, each with
varying specifica ons, performance, and capabili es.
3. The Raspberry Pi boards typically include HDMI ports for connec ng to displays, USB ports for
peripherals, GPIO pins for interfacing with sensors and actuators, audio output, and Ethernet
or Wi‐Fi connec vity for networking.

Opera ng System:

1. Raspberry Pi can run various opera ng systems, including Raspberry Pi OS (formerly known as
Raspbian), Ubuntu, and other Linux distribu ons.
2. Raspberry Pi OS is the official opera ng system op mized for Raspberry Pi boards. It is based
on Debian Linux and comes with pre‐installed so ware packages, development tools, and
u li es tailored for Raspberry Pi users.

Programming Languages and So ware:

1. Raspberry Pi supports mul ple programming languages, including Python, C/C++, Java, and
Scratch, making it suitable for a wide range of applica ons and projects.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
2. Users can develop so ware applica ons, games, u li es, and mul media projects using the
programming languages and development tools available on Raspberry Pi.
3. Raspberry Pi also supports various so ware packages and libraries for interfacing with
hardware peripherals, sensors, displays, and other electronic components.

Applica ons and Projects: Raspberry Pi is used in various applica ons and projects, including:

 Educa on: Raspberry Pi is widely used in schools, colleges, and universi es for teaching
computer science, electronics, and programming.
 DIY Projects: Raspberry Pi is popular among hobbyists, makers, and enthusiasts for building
home automa on systems, media centers, weather sta ons, and IoT devices.
 Prototyping: Raspberry Pi is used for prototyping and developing proof‐of‐concept projects in
fields such as robo cs, automa on, smart agriculture, and healthcare.
 Industrial Applica ons: Raspberry Pi is increasingly being adopted in industrial applica ons,
such as monitoring and control systems, data logging, and edge compu ng.

GPIO (General Purpose Input/Output) Pins:

 Raspberry Pi boards typically include a set of GPIO pins that can be configured as either digital
input or output pins.
 These pins can be used to interface with sensors, bu ons, LEDs, relays, motors, and other
electronic components.
 The number of GPIO pins varies depending on the model of Raspberry Pi board. For example,
the Raspberry Pi 4 Model B has 40 GPIO pins, while earlier models may have fewer pins.

Power Pins: Raspberry Pi boards feature several power pins that provide electrical power to the board
and connected devices. The main power pins include:

 5V (5 Volts): Provides regulated 5‐volt power output for external components.


 3.3V (3.3 Volts): Provides regulated 3.3‐volt power output for low‐power components.
 GND (Ground): Provides a reference voltage for electrical circuits and serves as a common
ground connec on.

USB Ports:

 Raspberry Pi boards typically include mul ple USB ports for connec ng peripherals such as
keyboards, mice, USB flash drives, webcams, and Wi‐Fi adapters.
 USB ports are used for data transfer and power supply to connected devices.

HDMI Port:

 Raspberry Pi boards feature an HDMI (High‐Defini on Mul media Interface) port for
connec ng to displays such as monitors, TVs, and projectors.
 HDMI ports support high‐defini on video and audio output, allowing users to use Raspberry
Pi for mul media applica ons and projects.

Ethernet Port:

 Some Raspberry Pi boards include an Ethernet port for wired network connec vity.
 The Ethernet port allows users to connect Raspberry Pi to a local network or the internet for
data communica on, remote access, and networking applica ons.

Camera and Display Ports:

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
 Raspberry Pi boards may include camera and display ports for connec ng official Raspberry Pi
camera modules and displays.
 These ports enable users to capture photos and videos, as well as display graphical user
interfaces (GUIs) and mul media content.

MicroSD Card Slot:

 Raspberry Pi boards use a microSD card slot for storing the opera ng system (OS), so ware
applica ons, and user data.
 Users can insert a microSD card containing the Raspberry Pi OS or other compa ble opera ng
systems to boot and run the Raspberry Pi.

Audio Jack:

 Some Raspberry Pi boards feature a 3.5mm audio jack for connec ng headphones, speakers,
or audio output devices.
 The audio jack allows users to play audio and sound effects, as well as interact with mul media
content.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
Installing NodeMCU (ESP8266) Board in the Arduino IDE
There are several development pla orms available for programming the ESP8266.

 Arduino IDE – intended for those who are familiar with Arduino

 Espruino – JavaScript SDK and firmware closely emulating Node.js

 Mongoose OS – An operating system for IoT devices that is recommended by Espressif


Systems and Google Cloud IoT

 MicroPython – Implementation of Python 3 for microcontrollers

When compared to other platforms, the Arduino IDE is the most user‐friendly for beginners.
Before you can use the Arduino IDE to program the ESP8266, you must first install the
ESP8266 board (also known as the ESP8266 Arduino Core) via the Arduino Board Manager.

process of downloading, installing, and testing the ESP8266 Arduino Core.

Step 1: Installing or Updating the Arduino IDE

Step 2: Installing the USB‐to‐Serial Bridge Driver

There are numerous ESP8266‐based development boards available. Depending on the design,
you may need to install additional drivers for your USB‐to‐serial converter before you are able
to upload code to your ESP8266.

Step 3: Installing the ESP8266 Arduino Core

Launch the Arduino IDE and navigate to File > Preferences.

Fill in the “Addi onal Board Manager URLs” field with the following.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
http://arduino.esp8266.com/stable/package_esp8266com_index.json

Then, click the “OK” bu on.

Now navigate to Tools > Board > Boards Manager…

Filter your search by entering ‘esp8266‘. Look for ESP8266 by ESP8266 Community. Click on
that entry, and then choose Install.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Step 4: Selecting the Board and Port

After installing the ESP8266 Arduino Core, restart your Arduino IDE and navigate
to Tools > Board to ensure you have ESP8266 boards available.

Now select your board in the Tools > Board menu (in our case, it’s the NodeMCU 1.0 (ESP‐12E
Module)). If you are unsure which board you have, select the Generic ESP8266 Module.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Finally, connect the ESP8266 NodeMCU to your computer and select the Port.

Step 5: Testing the Installation


The ESP8266 Arduino core includes several examples that demonstrate everything
from scanning for nearby networks to building a web server. To access the example sketches,
navigate to File > Examples > ESP8266.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
Aim: write a program to Blink LED using NodeMCU (ESP8266) development board in Sketch
This sketch uses the on‐board LED that most ESP8266 development boards have. This LED is
typically connected to digital pin D0

void setup()
{
pinMode(D0, OUTPUT);
}

void loop()
{
digitalWrite(D0, HIGH);
delay(500);
digitalWrite(D0, LOW);
delay(500);
}

AIM: demonstrates how to use the ESP8266WiFi library to scan nearby WiFi networks and
print the results.

#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200);
Serial.println(F("\nESP8266 WiFi scan example"));

// Set WiFi to station mode


WiFi.mode(WIFI_STA);

// Disconnect from an AP if it was previously connected


WiFi.disconnect();
delay(100);
}

void loop() {
String ssid;
int32_t rssi;
uint8_t encryptionType;
uint8_t* bssid;
int32_t channel;
bool hidden;

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
int scanResult;

Serial.println(F("Starting WiFi scan..."));

scanResult = WiFi.scanNetworks(/*async=*/false, /*hidden=*/true);

if (scanResult == 0) {
Serial.println(F("No networks found"));
} else if (scanResult > 0) {
Serial.printf(PSTR("%d networks found:\n"), scanResult);

// Print unsorted scan results


for (int8_t i = 0; i < scanResult; i++) {
WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel,
hidden);

Serial.printf(PSTR(" %02d: [CH %02d]


[%02X:%02X:%02X:%02X:%02X:%02X] %ddBm %c %c %s\n"),
i,
channel,
bssid[0], bssid[1], bssid[2],
bssid[3], bssid[4], bssid[5],
rssi,
(encryptionType == ENC_TYPE_NONE) ? ' ' : '*',
hidden ? 'H' : 'V',
ssid.c_str());
delay(0);
}
} else {
Serial.printf(PSTR("WiFi scan error %d"), scanResult);
}

// Wait a bit before scanning again


delay(5000);
}

Once uploaded the sketch, open the serial monitor at baud rate 115200 and press the RST
bu on on the ESP8266. Result is the SSID, RSSI, WiFi channel, and encryp on for each
discovered network.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
AIM: To interface ESP8266 NodeMCU and upload data HTTP POST using Arduino IDE and
ThingSpeak.
to program the ESP8266 NodeMCU using Arduino IDE, so make sure you have the ESP8266
add‐on installed.

HTTP POST Request Method


The Hypertext Transfer Protocol (HTTP) works as a request‐response protocol between a
client and server. Here’s an example:

POST is used to send data to a server to create/update a resource. For example, publish
sensor readings to a server.
The data sent to the server with POST is stored in the request body of the HTTP request:
POST /update HTTP/1.1
Host: example.com
api_key=api&field1=value1
Content-Type: application/x-www-form-urlencoded

In the body request, you can also send a JSON object:


POST /update HTTP/1.1
Host: example.com
{api_key: "api", field1: value1}
Content-Type: application/json

ESP8266 HTTP POST Data (ThingSpeak)

Using ThingSpeak API


ThingSpeak has a free API that allows you to store and retrieve data using HTTP. In this tutorial,
you’ll use the ThingSpeak API to publish and visualize data in charts from anywhere. As an
example, we’ll publish random values, but in a real applica on you would use real sensor
readings.
To use ThingSpeak API, you need an API key. Follow the next steps:
1. Go to ThingSpeak.com and create a free account.
2. Then, open the Channels tab.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
3. Create a New Channel.

4. Open your newly created channel and select the API Keys tab to copy your Write API
Key.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";


const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Domain Name with full URL Path for HTTP POST Request
const char* serverName = "http://api.thingspeak.com/update";
// Service API Key
String apiKey = "7HQJM49R8JAPR";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES


// For a final application, check the API call limits per hour/minute to avoid
getting blocked/banned
unsigned long lastTime = 0;
// Set timer to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Timer set to 10 seconds (10000)
unsigned long timerDelay = 10000;

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

void setup() {
Serial.begin(115200);

WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());

Serial.println("Timer set to 10 seconds (timerDelay variable), it will take


10 seconds before publishing the first reading.");

// Random seed is a number used to initialize a pseudorandom number


generator
randomSeed(analogRead(0));
}

void loop() {
//Send an HTTP POST request every 10 seconds
if ((millis() ‐ lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;

// Your Domain name with URL path or IP address with path


http.begin(client, serverName);

// Specify content‐type header


http.addHeader("Content‐Type", "application/x‐www‐form‐urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1=" +
String(random(40));
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);

/*
// If you need an HTTP request with a content type: application/json,
use the following:
http.addHeader("Content‐Type", "application/json");
// JSON data to send with HTTP POST
String httpRequestData = "{\"api_key\":\"" + apiKey + "\",\"field1\":\""
+ String(random(40)) + "\"}";

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);*/

Serial.print("HTTP Response code: ");


Serial.println(httpResponseCode);

// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

In the Arduino IDE serial monitor, you should see an HTTP response code of 200 (this means
that the request has succeeded).

ThingSpeak Dashboard should be receiving new random readings every 10 seconds.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
AIM: To interface ESP8266 NodeMCU and upload data HTTP POST using Arduino IDE and IFTTT.

to program the ESP8266 NodeMCU using Arduino IDE, so make sure you have the ESP8266
add‐on installed.
ESP8266 HTTP POST (IFTTT.com)
to trigger a web API to send email no fica ons. As an example, we’ll use the IFTTT.com API.
IFTTT has a free plan with lots of useful automa ons.

Using IFTTT.com Webhooks API


IFTTT stands for “If This Than That”, and it is a free web‐based service to create chains of
simple conditional statements called applets.
This means you can trigger an event when something happens. In this example, the applet
sends three random values to your email when the ESP8266 makes a request. You can replace
those random values with useful sensor readings.

Crea ng an IFTTT Account


If you don’t have an IFTTT account, go the IFTTT website: ifttt.com and enter your email to
create an account and get started. Creating an account on IFTTT is free!
Next, you need to create a new applet. Follow the next steps to create a new
applet:
1. Open the left menu and click the “Create” button.

2. Click on the “this” word. Search for the “Webhooks” service and select the Webhooks icon.
3. Choose the “Receive a web request” trigger and give a name to the event. In this case, I’ve
typed “test_event”. Then, click the “Create trigger” button.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
4. Click the “that” word to proceed. Now, define what happens when the event you’ve
defined is triggered. Search for the “Email” service and select it. You can leave the default
options.
5. Press the “Finish” button to create your Applet.

Tes ng Your Applet


Before proceeding with the project, it’s important to test your Applet first. Follow the next
steps to test it:

1. Search for Webhooks service or open this link: https://ifttt.com/maker_webhooks


2. Click the “Documentation” button.

A page showing your unique API key will show up.

3. Fill the “To trigger an Event with 3 JSON values” section with the event name created
previously, in our case test_event. Add some random values to the value1, value2, and value
3 fields. Then, click the “Test it” button.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

4. The event should be successfully triggered, and you’ll get a green message saying “Event
has been triggered”.
5. Go to your Email account. You should have a new email in your inbox from the IFTTT service
with the values you’ve defined in the previous step.
if you’ve received an email with the data entered in the test request, it means your Applet is
working as expected. Now, we need to program the ESP8266 to send an HTTP POST request
to the IFTTT service with the sensor readings.

Code ESP8266 HTTP POST Webhooks IFTTT.com


#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";


const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Domain Name with full URL Path for HTTP POST Request
// REPLACE WITH YOUR EVENT NAME AND API KEY ‐ open the documentation:
https://ifttt.com/maker_webhooks
const char* serverName =
"http://maker.ifttt.com/trigger/REPLACE_WITH_YOUR_EVENT/with/key/REPLACE_WITH_
YOUR_API_KEY";

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
// Example:
//const char* serverName =
"http://maker.ifttt.com/trigger/test_event/with/key/nAZjOphL3d‐ZO4N3k64‐
1A7gTlNSrxMJdmqy3tC";

// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES


// For a final application, check the API call limits per hour/minute to avoid
getting blocked/banned
unsigned long lastTime = 0;
// Set timer to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Timer set to 10 seconds (10000)
unsigned long timerDelay = 10000;

void setup() {
Serial.begin(115200);

WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());

Serial.println("Timer set to 10 seconds (timerDelay variable), it will take


10 seconds before publishing the first reading.");

// Random seed is a number used to initialize a pseudorandom number


generator
randomSeed(analogRead(0));
}

void loop() {
// Send an HTTP POST request every 10 seconds
if ((millis() ‐ lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;

// Your Domain name with URL path or IP address with path


http.begin(client, serverName);

// Specify content‐type header


http.addHeader("Content‐Type", "application/x‐www‐form‐urlencoded");

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things
// Data to send with HTTP POST
String httpRequestData = "value1=" + String(random(40)) + "&value2=" +
String(random(40))+ "&value3=" + String(random(40));
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);

/*
// If you need an HTTP request with a content type: application/json,
use the following:
http.addHeader("Content‐Type", "application/json");
// JSON data to send with HTTP POST
String httpRequestData = "{\"value1\":\"" + String(random(40)) +
"\",\"value2\":\"" + String(random(40)) + "\",\"value3\":\"" +
String(random(40)) + "\"}";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
*/

Serial.print("HTTP Response code: ");


Serial.println(httpResponseCode);

// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

A er uploading the code, open the Serial Monitor and you’ll see a message prin ng the HTTP
response code 200 indica ng that the request has succeeded.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)
DEPARTMENT OF COMPUTER SCIENCE & ENGG.
BHILAI INSTITUTE OF TECHNOLOGY, DURG (C.G.)
B. Tech 8 Sem Subject: Internet of Things

Go to your email account, and you should get a new email from IFTTT with three random
values. In this case: 38, 20 and 13.

Shiv Dutta Mishra, Assistant Professor (C.S.E.). Bhilai Ins tute of Technology, Durg (C.G.)

You might also like