Iot Minor Degree
Iot Minor Degree
Lab Manual
IoT Protocols
Department of
LAB MANUAL
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
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.
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.
Features,
• Of the 9, 4 pins can be used for SPI, and 2 pins for I2C.
• Do not use the 6 pins: CLK, SD0, CMD, SD1, SD2, SD3 (GPIO 6-11), because they are in
use.
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,
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.
Each ESP8266 module can operate as a station, so we can connect it to the WiFi network.
void loop() {
// put your main code here, to run repeatedly:
Quiz/Questions
_____________________________
(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?
_______________________________
___________________
(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
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() { }
#include <ESP8266WiFi.h>
WiFiClient client;
WiFiServer server(80);
#define led D5
void setup()
Serial.begin(9600);
WiFi.softAP("NodeMCU", "123456789");
Serial.println();
Serial.println("NodeMCU Started!");
Serial.println(WiFi.softAPIP());
server.begin();
pinMode(led, OUTPUT);
}
void loop()
client = server.available(); //Gets a client that is connected to the server and has data available for
reading.
if (client == 1)
Serial.println(request);
request.trim();
digitalWrite(led, HIGH);
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?
(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).
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).
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);
}
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:
(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.
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.
.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).
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()
// 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.
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";
// Start server
server.begin();
}
void loop() {
}
Conclusion:
Experiment-5
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>
// ----------------------------------------------------
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.
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.
#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
Conclusion:
Experiment-7
Apparatus: NodeMCUs
Theory:
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();
}
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);
}
}
}
}
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();
}
//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);
}
}
}
}
}
Aim: To make HTTP POST requests to post JSON data (DHT11) Data to Thing Speak.
Theory 1:
DHT11 sensor gives humidity and temperature data. It has got following pin interface.
Download the “Adafruit_Sensor-master” and “DHT_sensor_library” zip file and extract the same
and copy this to Arduino library folder.
Theory-2
“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.
• Open your newly created channel and select the API Keys tab to copy your API Key
Code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
// Domain Name with full URL Path for HTTP POST Request
// check the API call limits per hour/minute to avoid getting blocked/banned
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
Serial.println("");
Serial.println(WiFi.localIP());
randomSeed(analogRead(0));
void loop() {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
/*
// If need an HTTP req with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
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
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:
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:
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:
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>
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);
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
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?