[go: up one dir, main page]

0% found this document useful (0 votes)
169 views51 pages

Iot Minor Degree

The document provides instructions for connecting a NodeMCU development board to WiFi and implementing a soft access point. It includes code samples to connect the NodeMCU to an existing WiFi network and to set up the NodeMCU as an access point. The document also discusses using the NodeMCU as an access point to run a web server and control an LED.

Uploaded by

Kevin Modi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views51 pages

Iot Minor Degree

The document provides instructions for connecting a NodeMCU development board to WiFi and implementing a soft access point. It includes code samples to connect the NodeMCU to an existing WiFi network and to set up the NodeMCU as an access point. The document also discusses using the NodeMCU as an access point to run a web server and control an LED.

Uploaded by

Kevin Modi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

IoT Minor Degree

Lab Manual

IoT Protocols
Department of

Electronics & Communication Engineering

LAB MANUAL

CHARUTAR VIDYAMANDAL UNIVERSITY


INDEX

Practical
Topic
No.
1 To connect NodeMCU to WiFI.
To implement Soft API on NodeMCU (IOT node).
2
3 To Create a standalone web server that controls outputs
(two LEDs).
4 To build a web server with a slider to control the LED bright-
ness.
5 To create an SMS notification system that sends an SMS
when sensor readings are above or below a certain thresh-
old.
6 To make HTTP GET requests to get values and URL encoded
requests with IOT node.
7 To implement client-server communication between two
IOT nodes.
To make HTTP POST requests to post JSON data (DHT11) to
8 Thing Speak.
9 To send HTTP GET Request from NodeMCU ESP8266 to
Thing Speak Cloud
10 To implement Mosquitto MQTT Broker. To control LED and
Switch using MQTT
11 Project

G H PATEL COLLEGE OF ENGINEERING & TECHNOLOGY, Vallabh Vidyanagar


Experiment-1
Aim: To connect NodeMCU to WiFI
Apparatus: Node MCU, Arduino Software
Theory:

Introduction to NodeMCU
NodeMCU is an open source LUA based firmware developed for the ESP8266 Wi-Fi chip.
By exploring functionality with the ESP8266 chip, NodeMCU firmware comes with the ESP8266
Development board/kit i.e., NodeMCU Development board.
Since NodeMCU is an open-source platform, its hardware design is open for edit/modify/build. NodeMCU
Dev Kit/board consist of ESP8266 Wi-Fi enabled chip.

Since the summer of 2014, the ESP8266 has seen a wide adoption as a cost-effective solution for IoT
and Wi-Fi-capable devices.
The ESP8266 was developed by Espressif Systems, as a Serial (UART) to Wi-Fi SoC (System On a
Chip) based around a Tensilica Xtensa LX3 DPU.
This tiny IC includes an RF front end, RAM, and (usually) an onboard TCP/IP stack that allows it
ready to connect to a nearby Access Point, to act as an Access Point itself, or both. There is Version2
(V2) available for NodeMCU Dev Kit i.e. NodeMCU Development Board v1.0 (Version2), which usually
comes in black colored PCB.

Fig.1 ESP 8266 Node MCU-V1.0

NodeMCU Dev Kit has Arduino like Analog (i.e. A0) and Digital (D0-D8) pins on its board. It sup-
ports serial communication protocols i.e., UART, SPI, I2C, etc. Using such serial protocols, it can be
connected with serial devices like I2C enabled LCD display, Magnetometer HMC5883, MPU-6050
Gyro meter + Accelerometer, RTC chips, GPS modules, touch screen displays, SD cards, etc.

About the ESP8266 NodeMCU

Features,

• 80 MHz clock speed


• Operating voltage: 3.3V

• Storage flash memory: 4 MB, SRAM: 64 KB

• 9 common use digital GPIO pins labeled: D0 to D8.

• Of the 9, 4 pins can be used for SPI, and 2 pins for I2C.

• Interrupt GPIO pins D0-D8.

• Do not use the 6 pins: CLK, SD0, CMD, SD1, SD2, SD3 (GPIO 6-11), because they are in
use.

• Tested: button input using D0-D02.

• Tested: blink LED using D0-D08. Out to a resister, to an LED, to ground.

• Need to test, UART1 (TX = GPIO2), Serial1 object: D4 or D7 and D8.

NodeMCU with Arduino IDE

Applications can be developed on NodeMCU using the Arduino development environment. This
makes it easy for Arduino developers than learning a new language and IDE for NodeMCU such as
microPython.

Steps to be followed.

• In the Arduino IDE open the Preferences window and enter the URL below into the Addi-
tional Boards Manager URLs field and select OK.

http://arduino.esp8266.com/stable/package_esp8266com_index.json

• Select the menu option Tools → Board → Boards Manager... and scroll down and to locate
the option “esp8266 by ESP8266 Community” which should be the last item on the list and
click Install.

• Restarting the Arduino IDE, and select the board from the menu option,

Tools → Board → NodeMCU 1.0 (ESP-12E Module).

• After selecting the board follow settings below:-

Flash Size : "4M (3M SPIFFS)", Debug Port : "Disabled", Debug Level: "None"

IWIP Variant: "V2 Lower Memory", CPU Frequency: "80Mhz", Upload Speed:

"921600", Erase Flash: "Sketch On", Port : "COM port available" (where the device is con-
nected should show up)
• Now upload uploading an Example sketch as follows :- In IDE Goto >> Files >> Examples
>> ESP8266 >> Select the Blink Example and upload it . The on board LED should start to
blink.

• The on-board LED is connected to pin D0 of NodeMCU. External LED Pin can also be
connected to D0.

To work with NodeMCU its pin outs has to be known and also Arduino to ESP8266 Pin mapping.
Following is the list of NodeMCU's pin and corresponding Arduino pins.

D0 = 16, D1 = 5, D2 = 4, D3 = 0, D4 = 2, D5 = 14,
D6 = 12, D7 = 13, D8 = 15, D9 = 3 D10 = 1.

So to use pin D0 of NodeMCU you have to use Pin 16 in Arduino IDE.


WiFi modes
Devices that connect to WiFi network are called stations (STA). Connection to Wi-Fi is provided
by an access point (AP), that acts as a hub for one or more stations. The access point on the other
end is connected to a wired network. An access point is usually integrated with a router to provide
access from Wi-Fi network to the internet. Each access point is recognized by a SSID (Ser-
vice Set IDentifier), that essentially is the name of network you select when connecting a device
(station) to the WiFi.

Each ESP8266 module can operate as a station, so we can connect it to the WiFi network.

Part-I: Connecting Node MCU to Wi-Fi


#include <ESP8266WiFi.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
WiFi.begin("your SSID", "Your Password");
while(WiFi.status() != WL_CONNECTED)
{
Serial.print("..");
delay(200);
}
Serial.println();
Serial.println("NodeMCU is Connected!");
Serial.println(WiFi.localIP());

void loop() {
// put your main code here, to run repeatedly:

Quiz/Questions

(1) What is the error in this given line of code?


if(val=true){digitalWrite(4,HIGH)}
____________________________

(2) Which language is used to create a web server along C/C++?

_____________________________

(3) What is the correct syntax to include a library in the Arduino IDE?

_____________________________

(4) While writing a code for using ESP8266 with wifi, we need to specify the SSID. What is it?

_______________________________

(5) To which pin is the on-board LED of the ESP8266 connected?

___________________

(6) NodeMCU is an open source .......... based firmware for the ESP8266 WiFi SOC from Es-
pressif Systems. (Python, Lua, Java, None of these)

(7) The following code makes the pin D4 HIGH for how many seconds?
{digitalWrite(4,HIGH);
delay(10000);}

______________________________

(8) Name the chip used in the NodeMCU ESP8266 board which serves as the main
Controlling unit.
___________________
Experiment-2

Aim: To implement Soft Access Point on IOT node (NodeMCU)


Apparatus: Node MCU, Arduino Software
Theory:
WiFi modes

Each ESP8266 module can operate as a station, so we can connect it to the WiFi network. It can
also operate as a soft access point (soft-AP), to establish its own WiFi network. Therefore, we can
connect other stations to such modules. Third, ESP8266 is also able to operate both in station and
soft access point mode at the same time. This offers the possibility of building e.g. mesh networks.
Soft Access Point
An access point (AP) is a device that provides access to Wi-Fi network to other devices (stations)
and connects them further to a wired network. ESP8266 can provide similar functionality except it
does not have interface to a wired network. Such mode of operation is called soft access point (soft-
AP). The maximum number of stations connected to the soft-AP is five.

in this mode, ESP8266 will advertise its WiFi hotspot with a custom SSID and Password. Other
smart devices will be able to connect, and consequently establish communication with the ESP8266
WiFi module.
In this case, ESP8266 won’t be able to access the internet as it is merely advertising a WiFi hotspot.
Besides, the devices connected to the WiFi advertised by ESP8266 will only be able to communi-
cate with ESP8266 and not with any web server.

Program-1
#include <ESP8266WiFi.h> // Include the Wi-Fi library
const char *ssid = "ESP8266 Access Point"; // The name of the Wi-Fi network that will be created
const char *password = "thereisnospoon"; // The password required to connect to it
void setup() {
Serial.begin(115200);
delay(10);
Serial.println('\n');
WiFi.softAP(ssid, password); // Start the access point
Serial.print("Access Point \"");
Serial.print(ssid);
Serial.println("\" started");
Serial.print("IP address:\t");
Serial.println(WiFi.softAPIP()); // Send the IP address of the ESP8266 to the computer
}
void loop() { }

Part-II: Using NodeMCU as an Access Point and running a Web Server on it

#include <ESP8266WiFi.h>

WiFiClient client;

WiFiServer server(80);

#define led D5

void setup()

// put your setup code here, to run once:

Serial.begin(9600);

WiFi.softAP("NodeMCU", "123456789");

Serial.println();

Serial.println("NodeMCU Started!");

Serial.println(WiFi.softAPIP());

server.begin();

pinMode(led, OUTPUT);

}
void loop()

// put your main code here, to run repeatedly:

client = server.available(); //Gets a client that is connected to the server and has data available for
reading.

if (client == 1)

String request = client.readStringUntil('\n');

Serial.println(request);

request.trim();

if(request == "GET /ledon HTTP/1.1")

digitalWrite(led, HIGH);

if(request == "GET /ledoff HTTP/1.1")

digitalWrite(led, LOW);

}
On serial Port HTTP address will be available and using that address in web browser LED can be On
and OFF using “http address\ledon” & “http address\ledoff” command

Assignment/Questions:
(1) Which two libraries are required to create a web server using ESP8266?

(2) What is SSID?

(3) Which button in the NodeMCU is used to load the code again?
Experiment-3

Aim: To create a standalone web server that controls outputs (two LEDs).

Apparatus: NodeMCU, Arduino Software

Theory:
Web server is a place which stores, processes and delivers web pages to Web clients. Web client is
nothing but a web browser on our laptops and smartphones. The communication between client and
server takes place using a special protocol called Hypertext Transfer Protocol (HTTP).

HTTP Web Server Client Illustration


In this protocol, a client initiates communication by making a request for a specific web page using
HTTP and the server responds with the content of that web page or an error message if unable to do
so (like famous 404 Error). Pages delivered by a server are mostly HTML documents.

How to create a web server to control two outputs using Arduino IDE.

When a URL is typed in a web browser and hit ENTER, then the browser sends a HTTP re-
quest (a.k.a. GET request) to a web server. It’s a job of web server to handle this request by
doing something.

we are going to control things by accessing a specific URL. For example, suppose we en-
tered a URL like http://192.168.1.1/ledon in a browser. The browser then sends a HTTP re-
quest to ESP8266 to handle this request. When ESP8266 reads this request, it knows that
user wants to turn the LED ON. So, it turns the LED ON and sends a dynamic webpage to a
browser showing LED status : ON
Code:
// Load Wi-Fi library
#include <ESP8266WiFi.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";
// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output5, OUTPUT);
pinMode(output4, OUTPUT);
// Set outputs to LOW
digitalWrite(output5, LOW);
digitalWrite(output4, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client.");// print a message out in serial port
String currentLine = "";// make a String to hold incoming data client
currentTime = millis();
previousTime = currentTime;
while (client.connected() && currentTime - previousTime <= timeoutTime) {
// loop while the client's connected
currentTime = millis();
if (client.available()){// if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if current line is blank, then two newline characters in a row.
// end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers start with a response code (e.g. HTTP/1.1 200 OK)
// and content-type so client knows what's coming,then blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /5/on") >= 0) {
Serial.println("GPIO 5 on");
output5State = "on";
digitalWrite(output5, HIGH);
} else if (header.indexOf("GET /5/off") >= 0) {
Serial.println("GPIO 5 off");
output5State = "off";
digitalWrite(output5, LOW);
} else if (header.indexOf("GET /4/on") >= 0) {
Serial.println("GPIO 4 on");
output4State = "on";
digitalWrite(output4, HIGH);
} else if (header.indexOf("GET /4/off") >= 0) {
Serial.println("GPIO 4 off");
output4State = "off";
digitalWrite(output4, LOW);
}

// Display the HTML web page


client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" con tent=\"width=de-
vice-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// free to change the background-color and font-size to fit your preferences
client.println("<style>html { font-family: Helvetica; display: in-
line-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #195B6A; border: none;
color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin:
2px; cursor: pointer;}");
client.println(".button2 {background-color:
#77878A;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP8266 Web Server</h1>");

// Display current state, and ON/OFF buttons for GPIO 5


client.println("<p>GPIO 5 - State " + output5State + "</p>");
// If the output5State is off, it displays the ON button
if (output5State=="off") {
client.println("<p><a href=\"/5/on\"><button class=\"but-
ton\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/5/off\"><button class=\"button but-
ton2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 4
client.println("<p>GPIO 4 - State " + output4State + "</p>");
// If the output4State is off, it displays the ON button
if (output4State=="off") {
client.println("<p><a href=\"/4/on\"><button class=\"but-
ton\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/4/off\"><button class=\"button but-
ton2\">OFF</button></a></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') {
// if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Testing the Web Server
• upload the code,
• Open the Serial Monitor at a baud rate of 115200.
• Findi the NodeMCU IP Address using the Serial Monitor

Figure 2.1
• Copy that IP address, because you need it to access the web server.

• Accessing the Web Server. Open the browser and type the Node MCU IP address, and the
following page will be displayed as shown in below figure. This page is sent by the NodeMCU
when a request on the NodeMCU IP address is made.

Figure 2.2
• Take a look at the serial monitor as shown in figure 2.3. The NodeMCU receives
an HTTP request from a new client – in this case, it is the browser.
• Other information about the HTTP request such as HTTP header fields can be
also seen. They define the operating parameters of an HTTP transaction.

Figure 2.3

• Now Click the button to turn GPIO 5 ON. The NodeMCU receives a request on the /5/on
URL and turns LED 5 ON.

Figure 2.4
• The LED state is also updated on the web page.
Figure 2.5
• Test GPIO 4 button and check that it works in a similar way.

Conclusion:

Exercise:

(1) What are the advantages of client server network model?

(2) What is port 80?

(3) Modify the content of web page displayed on client with GPIO 1 and GPIO 2.
Experiment-4

Aim: To build a web server with a slider to control the LED brightness.

Apparatus: NodeMCU, Arduino Software

Theory:
▪ The Node MCU hosts a web server that displays a web page with a slider;
▪ When slider is moved, an HTTP request is made to the NodeMCU with the new
slider value;
▪ The HTTP request comes in the format: GET/slider?value=SLIDERVALUE, in
which SLIDERVALUE is a number between 0 and 1023. It can be modified to
include any other range;
▪ From the HTTP request, the NodeMCU gets the current value of the slider;
▪ The NodeMCU adjusts the PWM duty cycle accordingly to the slider value;
▪ This can be useful to control the brightness of an LED (as we’ll do in this exam-
ple), a servo motor, setting up a threshold value or other applications.

All the HTML text with styles included is stored in the index_html variable
The title is the text that shows up on the web browser tab.
Styles

Between the <style></style> tags, we add some CSS to style the web page.

<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 2.3rem;}
p {font-size: 1.9rem;}
body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}
.slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C;
outline: none; -webkit-transition: .2s; transition: opacity .2s;}
.slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px;
background: #003249; cursor: pointer;}
.slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; }
</style>
Basically, we’re setting the HTML page to display the text with Arial font in block without margin, and
aligned at the center.

Set the HTML body properties.

body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}


The following lines customize the slider:

.slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C;
outline: none; -webkit-transition: .2s; transition: opacity .2s;}
.slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px;
background: #003249; cursor: pointer;}
.slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; }

HTML Body

Inside the <body></body> tags is where we add the web page content.

The <h2></h2> tags add a heading to the web page. In this case, the “ESP Web Server” text, but you can
add any other text.
<h2>ESP Web Server</h2>
The first paragraph will contain the current slider value. That particular HTML tag has the id textSliderValue
assign to it, so that we can reference it later.

<p><span id="textSliderValue">%SLIDERVALUE%</span></p>
The %SLIDERVALUE% is a placeholder for the slider value. This will be replaced by the ESP8266 by an actual
value when it sends it to the browser. This is useful to show the current value when you access the browser
for the first time.

Creating a Slider

To create a slider in HTML you use the <input> tag. The <input> tag specifies a field where the user can en-
ter data.
There are a wide variety of input types. To define a slider, use the “type” attribute with the “range” value.
In a slider, you also need to define the minimum and the maximum range using the “min” and “max” at-
tributes (in this case, 0 and 1023, respectively).

<p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="1023"


value="%SLIDERVALUE%" step="1" class="slider"></p>
Finally, make an HTTP GET request.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();

For example, when the slider is at 0, you make an HTTP GET request on the following URL:
http://ESP-IP-ADDRESS/slider?value=0
And when the slider value is 200, you’ll have a request on the follow URL.

http://ESP-IP-ADDRESS/slider?value=200
This way, when the ESP8266 receives the GET request, it can retrieve the value parameter in the URL and
control the PWM signal accordingly as we’ll se in the next sections

Processor

Now, we need to create the processor () function, that will replace the placeholders in our HTML text with
the current slider value when you access it for the first time in a browser.
// Replaces placeholder with button section in your web page
String processor(const String& var){
//Serial.println(var);
if (var == "SLIDERVALUE"){
return sliderValue;
}
return String();
}
When the web page is requested, we check if the HTML has any placeholders. If it finds
the %SLIDERVALUE% placeholder, we return the value saved on the sliderValue variable.
setup()

In the setup(), initialize the Serial Monitor for debugging purposes.


Serial.begin(115200);
Set the duty cycle of the PWM signal to the value saved on the sliderValue (when the ESP8266 starts, it is
set to 0).
analogWrite(output, sliderValue.toInt());
To learn more about PWM with the ESP8266, read our guide: ESP8266 PWM with Arduino IDE (Analog Out-
put).
Connect to your local network and print the ESP8266 IP address.

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP Local IP Address
Serial.println(WiFi.localIP());
Handle Requests
Finally, add the next lines of code to handle the web server.

// Route for root / web page


server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});

// Send a GET request to <ESP_IP>/slider?value=<inputMessage>


server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
// GET input1 value on <ESP_IP>/slider?value=<inputMessage>
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
ledcWrite(ledChannel, sliderValue.toInt());
}
else {
inputMessage = "No message sent";
}
Serial.println(inputMessage);
request->send(200, "text/plain", "OK");
});
When we make a request on the root URL, we send the HTML text that is stored on the index_html varia-
ble. We also need to pass the processor() function, that will replace all the placeholders with the right val-
ues.
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
We need another handler that will save the current slider value and set he LED brightness accordingly.

server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {


String inputMessage;
// GET input1 value on <ESP_IP>/slider?value=<inputMessage>
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
ledcWrite(ledChannel, sliderValue.toInt());
}
else {
inputMessage = "No message sent";
}
Serial.println(inputMessage);
request->send(200, "text/plain", "OK");
});
Basically, we get the slider value on the following lines:
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
Then, update the LED brightness (PWM duty cycle) using the ledcWrite() function that accepts as argu-
ments the channel you want to control and the value.
ledcWrite(ledChannel, sliderValue.toInt());
Lastly, start the server.

server.begin();
Because this is an asynchronous web server, we don’t need to write anything in the loop().
void loop(){

}
Upload the Code

Now, upload the code to your ESP8266. Make sure you have the right board and COM port selected.

After uploading, open the Serial Monitor at a baud rate of 115200. Press the ESP8266 reset button. The
ESP8266 IP address should be printed in the serial monitor.
Web Server Demonstration

Open a browser and type the ESP8266 IP address. Your web server should display the slider and its current
value.
Code:
// Import required libraries
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const int output = 2;
String sliderValue = "0";
const char* PARAM_INPUT = "value";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP Web Server</title>
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 2.3rem;}
p {font-size: 1.9rem;}
body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}
.slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C;
outline: none; -webkit-transition: .2s; transition: opacity .2s;}
.slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px;
background: #003249; cursor: pointer;}
.slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; }
</style>
</head>
<body>
<h2>ESP Web Server</h2>
<p><span id="textSliderValue">%SLIDERVALUE%</span></p>
<p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="1023"
value="%SLIDERVALUE%" step="1" class="slider"></p>
<script>
function updateSliderPWM(element) {
var sliderValue = document.getElementById("pwmSlider").value;
document.getElementById("textSliderValue").innerHTML = sliderValue;
console.log(sliderValue);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";

// Replaces placeholder with button section in your web page


String processor(const String& var){
//Serial.println(var);
if (var == "SLIDERVALUE"){
return sliderValue;
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
analogWrite(output, sliderValue.toInt());
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Send a GET request to <ESP_IP>/slider?value=<inputMessage>
server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
// GET input1 value on <ESP_IP>/slider?value=<inputMessage>
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
analogWrite(output, sliderValue.toInt());
}
else {
inputMessage = "No message sent";
}
Serial.println(inputMessage);
request->send(200, "text/plain", "OK");
});

// Start server
server.begin();
}
void loop() {
}

Conclusion:
Experiment-5

Aim: To Send an SMS Using an ESP8266/NodeMCU

Apparatus: NodeMCU

Theory:
To send an SMS messages over the internet from an ESP8266 NodeMCU module
board, to a mobile phone following are the instructions.
First there is a need to get a virtual phone number from Twilio, a communica-
tions company. No credit card needed because Twilio has free Trial account op-
tion. Then, you will download and use a sample Arduino IDE program to send
SMS messages
Twilio is an internet communications platform company. The products being used in
this instructable are Twilio Programmable Messaging and phone numbers. Twilio
has a inventory of virtual phone numbers that can be used to send and receive SMS
messages to any mobile phone.
• Open a Twilio account, if you don't have one. Trial account will have a
trial balance that is used to pay for phone numbers and exchanging text
messages with mobile phones.
• Buy a Twilio phone number. It's free because it's paid for using your trial
balance.
• Send a message from your mobile phone to your new phone number.
• Once Twilio receives your message, an automated response message is
sent to your mobile phone.

Code:

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

// Your network SSID and password


const char* ssid = “MiA3”;
const char* password = “mbshah1976”;

const char* account_sid = “AC56e736d9a1bb7ece9972ce28fe76843e”;


const char* auth_token = “91266a96ec5766f2dbd503238732d7e1”;
String from_number = “+918160378196”;
String to_number = “+919408033700”;
String message_body = “Hello from the NodeMCU.”;

// Find the api.twilio.com SHA1 fingerprint using,


// echo | openssl s_client -connect api.twilio.com:443 | openssl x509 -fingerprint
const char fingerprint[] = “BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0”;

String urlencode(String str) {


String encodedString = “”;
char c;
char code0;
char code1;
char code2;
for (int I = 0; I < str.length(); i++) {
c = str.charAt(i);
if (c == ‘ ‘) {
encodedString += ‘+’;
} else if (isalnumI) {
encodedString += c;
} else {
code1 = (c & 0xf) + ‘0’;
if ((c & 0xf) > 9) {
code1 = (c & 0xf) – 10 + ‘A’;
}
c = (c >> 4) & 0xf;
code0 = c + ‘0’;
if (c > 9) {
code0 = c – 10 + ‘A’;
}
code2 = ‘\0’;
encodedString += ‘%’;
encodedString += code0;
encodedString += code1;
}
yield();
}
return encodedString;
}

String get_auth_header(const String& user, const String& password) {


size_t toencodeLen = user.length() + password.length() + 2;
char toencode[toencodeLen];
memset(toencode, 0, toencodeLen);
snprintf(toencode, toencodeLen, “%s:%s”, user.c_str(), password.c_str());
String encoded = base64::encode((uint8_t*)toencode, toencodeLen – 1);
String encoded_string = String(encoded);
std::string::size_type I = 0;
// Strip newlines (after every 72 characters in spec)
while (I < encoded_string.length()) {
I = encoded_string.indexOf(‘\n’, i);
if (I == -1) {
break;
}
encoded_string.remove(I, 1);
}
return “Authorization: Basic “ + encoded_string;
}
void setup() {
Serial.begin(115200); // 115200 or 9600
delay(1000); // Give the serial connection time to start before the first print.
Serial.println(“”); // Newline after garbage characters.
Serial.println(F(“+++ Setup.”));

// ----------------------------------------------------
Serial.println(“+ Connect to WiFi. “);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(“.”);
}
Serial.println(“”);
Serial.print(“+ Connected to WiFi, IP address: “);
Serial.println(WiFi.localIP());

// ----------------------------------------------------
// Use WiFiClientSecure to create a TLS 1.2 connection.
// Note, using a cert fingerprint is required.
WiFiClientSecure client;
client.setFingerprint(fingerprint);
Serial.printf(“+ Using fingerprint ‘%s’\n”, fingerprint);
const char* host = “api.twilio.com”;
const int httpsPort = 443;
Serial.print(“+ Connecting to “);
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println(“- Connection failed.”);
return; // Skips to loop();
}
Serial.println(“+ Connected.”);
Serial.println(“+ Post an HTTP send SMS request.”);
String post_data = “To=” + urlencode(to_number)
+ “&From=” + urlencode(from_number)
+ “&Body=” + urlencode(message_body);
String auth_header = get_auth_header(account_sid, auth_token);
String http_request = “POST /2010-04-01/Accounts/” + String(account_sid) + “/Messages
HTTP/1.1\r\n”
+ auth_header + “\r\n”
+ “Host: “ + host + “\r\n”
+ “Cache-control: no-cache\r\n”
+ “User-Agent: ESP8266 Twilio Example\r\n”
+ “Content-Type: application/x-www-form-urlencoded\r\n”
+ “Content-Length: “ + post_data.length() + “\r\n”
+ “Connection: close\r\n”
+ “\r\n”
+ post_data
+ “\r\n”;
client.println(http_request);
// Read the response.
String response = “”;
while (client.connected()) {
String line = client.readStringUntil(‘\n’);
response += (line);
response += (“\r\n”);
}
Serial.println(“+ Connection is closed.”);
Serial.println(“+ Response:”);
Serial.println(response);

// ---------------------------------------------------------------------------
Serial.println(F(“+ Starting the loop.”));
}

void loop() {
delay(1000);
}
Send an SMS Using an ESP8266 : 5 Steps - Instructables

Conclusion:
Experiment-6

Aim: To make HTTP GET requests to get values and URL encoded requests with IOT node.

Apparatus: NodeMCU, Thing Speak Cloud, Arduino IDE

Theory:

1) Here local time values will be imported from website and will be monitored through
ThingHTTP app
2) To get local time data go to following website http://worldtimeserver.com/cur-
rent_time_in_IN.aspx
3) Right click and go to inspect option

4) A tab will be created on the right of your screen with series of programming codes inside. If
you select the value correctly, there will be a line of code that is highlighted in blue. Go to
the line of code, Right click and select copy, and copy to Xpath

5) The next step is signing up or logging into the ThingSpeak official website. Once account
has been created, Go to Apps tab and select ThingHTTP. Click “NEW ThingHTTP” button
and named it as CURRENT TIME.
6) key in the URL link (The website link where you get the value) and also paste the Xpath
code under Parse String.
7) Once you have clicked the “save ThingHTTP”, on the right side of the page will create
a REST API link. Copy the whole link (Excluding the word GET) and paste on another
empty web browser page and see whether the parse value is response correctly. If response
correctly, there will shown some values which consists of values that we want to copy.

8) Copy below code in Arduino and run the program


Code:

#include <ESP8266WiFi.h>
const char* host = "api.thingspeak.com";
int value = 1;
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
//Serial.println(ssid);
WiFi.begin("MiA3", "mbshah1976");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}//end setup

void loop() {
delay(5000);
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient Client;
const int httpPort = 80;
if (!Client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request

String url = "/apps/thinghttp/send_request?api_key=OCR91ZM7AOGZX976";


Serial.println(host + url);
Serial.println(String("TRY: ") + value + ".");
// This will send the request to the server
Client.print(String("GET ") + url + "&headers=false" + " HTTP/1.1\r\n" + "Host: " + host +
"\r\n" + "Connection: close\r\n\r\n");
delay(2000);
// Read all the lines of the reply from server and print them to Serial
while(Client.available()){
String line = Client.readStringUntil('\r');
Serial.println(line);
}
Serial.println("");
Serial.println(String("Try nr. ") + value + " is finished.");
Serial.println("Waiting for next try...");
Serial.println("");
value = value + 1;
delay(20000);
}

Conclusion:
Experiment-7

Aim: To implement client-server communication between two IOT nodes.

Apparatus: NodeMCUs

Theory:

The NodeMCU ESP8266 is a small microcontroller with a Wifi chip. It is possible


to establish a communication between two ESP8266, when they are connected on
the same network. In Master/Slave architecture, an ESP8266 will play the role of
a server and manage a Web interface as well as the various “slave” requests.

For the Master microcontroller, we will create a server to manage the browser re-
quests, the web interface and the requests coming from the slave microcontrollers.
We use the ESP8266WiFi.h library which allows the management of the WiFi
chip for the ESP8266 cards
Code:

Master/Server Code

#include <ESP8266WiFi.h>
#define NUM_SLAVES 1
#define LED D4

//Parameters
String nom = "Master";

#include <ESP8266WiFi.h>
const char* ssid = "*******";
const char* password = "**********";

//Variables
bool sendCmd = false;
String slaveCmd = "0";
String slaveState = "0";

//Objects
WiFiServer server(80);
WiFiClient browser;
IPAddress ip(192, 168, 1, 44);
IPAddress gateway(192, 168, 1, 254);
IPAddress subnet(255, 255, 255, 0);

void setup() {
//Init Serial USB
Serial.begin(115200);
Serial.println(F("Initialize System"));
//Init ESP8266 Wifi
WiFi.config(ip, gateway, subnet); // forces to use the fix IP
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
server.begin();
Serial.print(nom);
Serial.print(F(" connected to Wifi! IP address : http://"));
Serial.println(WiFi.localIP()); // Print the IP address
pinMode(LED, OUTPUT);
}

void loop() {
clientRequest();
}

void clientRequest( ) { /* function clientRequest */


////Check if client connected
WiFiClient client = server.available();
client.setTimeout(50);
if (client) {
if (client.connected()) {
//Print client IP address
Serial.print(" ->");Serial.println(client.remoteIP());
String request = client.readStringUntil('\r'); //receives the message from the client

if (request.indexOf("Slave0") == 0) {
//Handle slave request
Serial.print("From "); Serial.println(request);
int index = request.indexOf(":");
String slaveid = request.substring(0, index);
slaveState = request.substring(request.indexOf("x") + 1, request.length());
Serial.print("state received: "); Serial.println(slaveState);
client.print(nom);
if (sendCmd) {
sendCmd = false;
client.println(": Ok " + slaveid + "! Set state to x" + String(slaveCmd) + "\r");
} else {
client.println(": Hi " + slaveid + "!\r"); // sends the answer to the client
}
client.stop(); // terminates the connection with the client
} else {
Serial.print("From Browser : "); Serial.println(request);
client.flush();
handleRequest(request);
webpage(client);
}
}
}
}

void handleRequest(String request) { /* function handleRequest */


////Check if client connected
if (request.indexOf("/light1on") > 0) {
digitalWrite(LED, LOW);
}
if (request.indexOf("/light1off") > 0) {
digitalWrite(LED, HIGH);
}
if (request.indexOf("/light2on") > 0) {
sendCmd = true;
slaveCmd = "1";
}
if (request.indexOf("/light2off") > 0) {
sendCmd = true;
slaveCmd = "0";
}
}

void webpage(WiFiClient browser) { /* function webpage */


////Send webpage to browser
browser.println("HTTP/1.1 200 OK");
browser.println("Content-Type: text/html");
browser.println(""); // do not forget this one
browser.println("<!DOCTYPE HTML>");
browser.println("<html>");
browser.println("<head>");
browser.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
browser.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translu-
cent' />");
browser.println("</head>");
browser.println("<body style = ' background-color:#000000; color:white;'>");
browser.println("<hr/><hr>");
browser.println("<h1><center> Esp8266 Electrical Device Control </center></h1>");
browser.println("<hr/><hr>");
browser.println("<br><br>");
browser.println("<br><br>");
browser.println("<h2> Commands </h2>");
browser.println("<center>");
browser.println("Built-in LED");
browser.println("<a href='/light1on'><button>Turn On </button></a>");
browser.println("<a href='/light1off'><button>Turn Off </button></a><br />");
browser.println("</center>");
browser.println("<br><br>");
browser.println("<center>");
browser.println("Device 2");
browser.println("<a href='/light2on'><button>Turn On </button></a>");
browser.println("<a href='/light2off'><button>Turn Off </button></a><br />");
browser.println("</center>");
browser.println("<br><br>");
browser.println("<br><br>");
browser.println("<h2> Data </h2>");
browser.println("<center>");
browser.println("<table border='5'>");
browser.println("<tr>");
if (digitalRead(LED))
{
browser.print("<td>LED is OFF</td>");
}
else
{
browser.print("<td>LED is ON</td>");
}
browser.println("<br />");
if (slaveState == "1") //(digitalRead(4))
{
browser.print("<td>Light 2 is OFF</td>");
}
else
{
browser.print("<td>Light 2 is ON</td>");
}
browser.println("</tr>");
browser.println("</table>");
browser.println("</center>");
browser.println("</body></html>");
delay(1);
}

In the slave code, we will connect to the server using the IP address previously used.

Slave/Client Code

#include <ESP8266WiFi.h>

//Constants
#define LED D4
#define UPDATE_TIME 500

//Parameters
String nom = "Slave0";
const char* ssid = "*******";
const char* password = "*******";
//Variables
String command;
unsigned long previousRequest = 0;

//Objects
WiFiClient master;
IPAddress server(192, 168, 1, 44);

void setup() {
//Init Serial USB
Serial.begin(115200);
Serial.println(F("Initialize System"));
//Init ESP8266 Wifi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.print(nom);
Serial.print(F(" connected to Wifi! IP address : ")); Serial.println(WiFi.localIP()); // Print the
IP address
pinMode(LED, OUTPUT);
}

void loop() {
requestMaster();
}

void requestMaster( ) { /* function requestMaster */


////Request to master
if ((millis() - previousRequest) > UPDATE_TIME) { // client connect to server every 500ms
previousRequest = millis();

if (master.connect(server, 80)) { // Connection to the server


master.println(nom + ": Hello! my current state is x" + String(!digitalRead(LED)) + "\r");

//answer
String answer = master.readStringUntil('\r'); // receives the answer from the sever
master.flush();
Serial.println("from " + answer);
if (answer.indexOf("x") >= 0) {
command = answer.substring(answer.indexOf("x") + 1, answer.length());
Serial.print("command received: "); Serial.println(command);
if (command == "1") {
Serial.println("LED ON");
digitalWrite(LED, LOW);
} else {
Serial.println("LED OFF");
digitalWrite(LED, HIGH);
}
}
}
}
}

Communication between two ESP8266 via WiFi • AranaCorp


When the microcontrollers are connected to the Wifi and the communication between the two
ESP8266 is established, we can see that information and commands are exchanged between the
two boards. It is also possible to control the LEDs on both boards using the buttons on the inter-
face.
Conclusion:
Experiment-8

Aim: To make HTTP POST requests to post JSON data (DHT11) Data to Thing Speak.

Apparatus: NodeMCU, DHT11

Theory 1:

DHT11 Temperature & Humidity sensor on NodeMCU using Arduino IDE.

DHT11 sensor gives humidity and temperature data. It has got following pin interface.

Make the following connections –

Download the “Adafruit_Sensor-master” and “DHT_sensor_library” zip file and extract the same
and copy this to Arduino library folder.

Code: DHT11 Program


#include "DHT.h" // including the library of DHT11 temperature and humidity sensor
#define DHTTYPE DHT11 // DHT 11
#define dht_dpin 0
DHT dht(dht_dpin, DHTTYPE);
void setup(void)
{
dht.begin();
Serial.begin(9600);
Serial.println("Humidity and temperature\n\n");
delay(700);
}
void loop() {
float h = dht.readHumidity();
float t = dht. readTemperature();
Serial.print("Current humidity = ");
Serial.print(h);
Serial.print("% ");
Serial.print("temperature = ");
Serial.print(t);
Serial.println("C ");
delay(800);
}

Theory-2

ESP8266 HTTP POST Data (ThingSpeak)


In this example, ESP8266 makes an HTTP POST request to send a new value to Thing Speak.

“Thing Speak” has a free API that allows to store and retrieve data using HTTP. Thing Speak API
can be used to publish and visualize data in charts from anywhere. In below example, random values
will be published instead of real sensor readings.

Follow the next steps to use Thing Speak API:

• Go to ThingSpeak.com and create a free account.


• Then, open the Channels tab.

• Create a New Channel

• Open your newly created channel and select the API Keys tab to copy your API Key

• Code following code for ESP8266 HTTP POST ThingSpeak

Code:

#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 = " REPLACE_WITH_YOUR_API_KEY";

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

// 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("10 sec before publishing the first reading.");

// Random seed is a number used to initialize a random 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){

HTTPClient http;

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

http.begin(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 need an HTTP req 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))
+ "\"}";

// 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();To which pin is the on board LED of the ESP8266 connected?

Conclusion:
Experiment-9

Aim: To send HTTP GET Request from NodeMCU ESP8266 to Thing Speak Cloud

Apparatus: Node MCU, DHT11

Theory: An HTTP client sends an HTTP request to a server in the form of a request message.
The request method indicates the method to be performed on the resource identified by the
given Request-URI. The method is case-sensitive and should always be mentioned in upper-
case.

GET

The GET method is used to retrieve information from the given server using a given URI. Re-
quests using GET should only retrieve data and should have no other effect on the data

PUT

Replaces all the current representations of the target resource with the uploaded content.

Request-URI

The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to
apply the request. Following are the most commonly used forms to specify an URI:

Request-URI = "*" | absoluteURI | abs_path | authority

1) The asterisk * is used when an HTTP request does not apply to a particular resource, but to
the server itself, and is only allowed when the method used does not necessarily apply to a
resource. For example:

OPTIONS * HTTP/1.1

2) The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is re-
quested to forward the request or service from a valid cache, and return the response. For
example:

GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1

3) The most common form of Request-URI is that used to identify a resource on an origin
server or gateway. For example, a client wishing to retrieve a resource directly from the
origin server would create a TCP connection to port 80 of the host "www.w3.org" and send
the following lines:

GET /pub/WWW/TheProject.html HTTP/1.1


Host: www.w3.org

Note that the absolute path cannot be empty; if none is present in the original URI, it MUST
be given as "/" (the server root).

Code:

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

DHT dht(D5, DHT11);

String host = "api.thingspeak.com";


int httpPort = 80;
String url1 = "/update?api_key=G940T96IE24HT2PA&field1=";
String url2 = "/update?api_key=G940T96IE24HT2PA&field2=";

HTTPClient http;

oid setup()
{
Serial.begin(9600);
WiFi.begin("iot", "project1234");
while(WiFi.status() != WL_CONNECTED)
{
delay(200);
Serial.print("..");
}
Serial.println();
Serial.println("NodeMCU is connected!");
Serial.println(WiFi.localIP());
dht.begin();
}

void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.println("Temperature: " + (String) t);
Serial.println("Humidity: " + (String) h);

url1 = url1 + (String) t;


http.begin(host,httpPort,url1);
int httpCode = http.GET();
Serial.println(httpCode);
delay(2000);

url2 = url2 + (String) h;


http.begin(host,httpPort,url2);
httpCode = http.GET();
Serial.println(httpCode);
delay(2000);
}

Conclusion:
Experiment: 10
Aim: To implement Mosquitto MQTT Broker on Raspberry Pi
Apparatus: Raspberry Pi
Theory:
MQTT BROKER LOCALLY ON RASPBERRY PI
we will be installing the MQTT broker in Raspberry pi and use it locally.
A broker is the central part of the MQTT network, which is responsible for receiving all the mes-
sages and then forward the messages to the subscribed devices. The broker is also responsible for
deciding which message to send to which devices, as it already has the information of devices, i.e.,
devices have already subscribed to different topics.
We will be installing the Mosquitto broker, which is an open-source message broker that imple-
ments the MQTT protocol versions 5.0 and 3.1.
Run the following commands on raspberry Pi

1) Install Mosquitto Broker on Raspberry pi

2) sudo apt-get update

3) sudo apt install -y mosquitto mosquitto-clients

4) sudo systemctl enable mosquitto.service (run automatically on boot)

5) mosquitto -d ( Run mosquito in the background )

6) mosquitto_sub -d -t Highvoltages (test the broker by subscribing to a topic)


open another shell window and type,
7) mosquitto_pub -d -t Highvoltages -m "Hello world!"

and you will see the message in the first window.

Secure MQTT broker

We can set the user name and password by typing,


mosquitto_passwd -c passwordfile pi

and it will ask us for the password.


We can enter the password for user pi, and it will be protected.
Now let’s check our broker from our laptop. Make sure pi and pc are on the same network.
Get the pi IP first by typing ifconfig and
download the MQTT explorer software.

Now make the connection with ip address, user name and password and then connect.
After connection publish some thing using MQTT explorer. This should be visible on raspberry pi
subscriber window.

Questions
1.) What are the different levels of QOS for MQTT protocol?

You might also like