4th Unit IoT
4th Unit IoT
1. Initialize the necessary hardware components and establish a connection to the internet using a
network module, such as a Wi-Fi or Ethernet shield.
2. Collect data from your sensors and store it in appropriate variables or data structures.
3. Format the data into a suitable format for transmission, such as JSON or XML.
4. Use an HTTP client library to create an HTTP POST request to the web server.
5. Include the formatted sensor data as the payload of the POST request.
6. Send the POST request to the web server using the HTTP client library.
7. Receive and handle any response from the web server, such as an acknowledgment or error
message.
What is a Payload in an API? The payload of an API is the
data you are interested in transporting to the server when you
make an API request. Simply put, it is the body of your HTTP
request and response message. For a better understanding,
imagine sending the message, "Hello" and labeling it "msg"
(short for message).03-Aug-2022
Both JSON and XML can be used to receive data from a web server.
The following JSON and XML examples both define an employee object, with
an array of 3 employees:
JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 80
int main(void) {
char payload[100];
char post_request[500];
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
char response[1024];
close(socket_fd);
return 0;
THE INTERNET
To get you geared up for our project, let us see first how the internet works.
The internet, as we know it, is a global WAN (Wide Area Network) that connects
computers around the world. Physically, they are just wires under the ground. A web
server is capable of connecting to these “wires” directly. On the other hand, a web client
needs to go through a server first to connect to another server or client.
Additionally, a web server that can be accessed anywhere via the internet is called
a global server. Meanwhile, a web server that can only be visited in your Local Area
Network (LAN) is called a local server.
WEB REQUESTS
To get data from web servers, web clients use HTTP requests. There are several types
of HTTP requests, but you only need to learn two to create an Arduino server. These
requests are called HTTP GET and HTTP POST.
HTTP GET is a web request that retrieves data from a web browser. It does not change
anything on the server. It just fetches the data from it.
HTTP POST is a web request that transmits data to the server. It adds something new to
the server.
A typical example of a GET request is the simple browsing of a website. On the other
hand, POST requests are used in typing text into a web page, for instance, a username
and password.
THE ESP8266-01 MODULE
The ESP8266 is a WiFi chip developed by Espressif Systems. It provides a full WiFi
networking solution, enabling users to set up a web server or web client with a separate
processor or even standalone. It is also Arduino compatible, meaning you can program it
using the Arduino IDE.
We are going to use the ESP-01 version module of the chip. It is developed by a third-
party manufacturer called AI-Thinker. It has an onboard MCU (Microcontroller Unit),
which allows users to control I/O digital pins directly via the Arduino IDE.
TECHNICAL SPECIFICATIONS
802.11 b/g/n
Support Smart Link Function for both Android and iOS devices
Support Smart Link Function for both Android and iOS devices
SDIO 2.0, (H) SPI, UART, I2C, I2S, IRDA, PWM, GPIO
ESP8266 PINOUT
ESP8266 PINOUT
Legend:
1. GND – Ground
2. GPIO2 – Programmable I/O pin with an internal pull-up resistor
3. GPIO0 – Programmable I/O pin with an internal pull-up resistor
4. RX – UART Receiving pin
5. VCC – 3.3v
6. REST – External Reset Pin, Active LOW
7. CH_PD – Chip Enable Pin. Active HIGH
8. TX – UART Transmitting pin
SETTING UP A LOCAL SERVER
Before we create a global server, we need to understand how a local server works. In
order to set up a local server, we need to find a way to send AT commands to the ESP-
01. These commands come from the pre-installed AT firmware of the ESP-01. We can
either use an FTDI cable to send these directly or we can use a separate processor like
the Arduino. In this tutorial, we are going to use an Arduino.
First, you need the following components:
Arduino Uno
ESP8266 ESP-01 module
Two 1K Ohm resistors
Breadboard
Jumper wires
Then, connect the ESP-01 to the Arduino, as shown below:
The maximum voltage input of the ESP8266-01 is 3.6V. Always double-check the pins
when connecting it to the 3.3V power supply. If you accidentally connect it to the 5-V
supply, you risk destroying the module.
Both 1k resistors act as pull up and pull down resistors for the CH_PD and RX pins,
respectively.
USING THE ARDUINO IDE
After preparing the hardware, let’s now proceed to the programming.
Open the Arduino IDE. Go to File >> Examples >> Basics >> BareMinimum then upload
the sketch. This is to make sure that no program is running on the Arduino board.
Next, open the serial monitor. Make sure to set the baud rate to default, which is usually
115200. Then, type the following AT command: AT.
SP8266 AT COMMANDS
The ESP8266 AT Commands allow users to perform operations like testing the
connection, setting the mode of operation, connecting to WiFi, determining the IP
address, etc.
In the first mode, you set the WiFi module to act as a Station (STA). The module gains
the ability to connect to an available WiFi network.
In the second mode, you set the WiFi module to act as an Access Point (AP). The
module acts as a WiFI network where devices like computers can connect to it.
In the third mode, you set the WiFi module to act as both an AP and an STA.
We need to set the module to AP mode if we are going to use it as a web server. To
check what mode the ESP8266 is in, type in AT+CWMODE?. The response is going to be
number 1, 2, or 3 which corresponds to the mode of operation.
CONNECTING TO WIFI
To connect to a WiFi network, type the following command: AT+CWJAP=
“SSID”,“Password”
These are case sensitive, so be sure to type the exact WiFi Network’s name and
password. Also, there should be no spaces between the quotation marks and the
comma. You are going to get an OK response when successfully connected.
At this point, we already established a connection between your home router and the
ESP-01. We are now ready to send HTTP requests from your computer to the module.
Notice that your web browser isn’t displaying anything. That’s because there is still no
data to be retrieved.
Let us send the usual “Hello World” to test our connection. Type the following command
in your serial monitor: AT+CIPSEND=0,12
The first number indicates what channel the data is going to be transmitted. While the
second number indicates the number of characters to be sent. Since we are going to
send “Hello World”, we need to set the second number to 12 so that it is sent entirely,
including space.
After pressing enter, a > symbol should appear. This means that the server is already
waiting for the message. Next, type Hello World on your serial monitor. After a while, the
monitor will display SEND OK. Finally, to display the data on your web browser, close
the communication channel by typing the following command: AT+CIPCLOSE=0.
As soon as you hit enter, a Hello World message should appear on your web browser.
Using the parts listed below, build your Arduino and ESP8266 ESP-01 module as shown
in the image below:
Arduino Uno
ESP8266 ESP-01 module
DHT22 temperature and humidity sensor
Two 10K Ohm resistors
One 1K Ohm resistor
One 2.2K Ohm resistor
Breadboard
Jumper wires
Previously, we used the serial monitor to send AT commands to the ESP-01. This time
we will do the actual programming.
Next, we power up the DHT22. The DHT22 module needs 3.3V – 5V to work. You can
connect it to either supply. If you wish to use 5V, connect it to pin before the voltage
divider. Then, use a 10k pull-up resistor along the data line that connects the DHT22 and
the ESP-01.
Then, to initialize the ESP-01 module, connect the EN/CH-PD (Enable) pin to the 3.3V
supply. Use a 10k pull-up resistor.
Finally. connect the ESP-01’s GPIO pin 0 to GND to start program mode.
3. Go to Tools >> Board >> Boards Manager.
4. In the Boards Manager search bar, enter ESP8266. Then, press install on the
“ESP8266 by ESP8266 Community“.
At this point, ESP8266 board definitions are already installed. You can now program the
ESP8266 chip just like any other Arduino board.
The DHT.h library is a library from Adafruit that enables support for DHT temperature
and humidity sensors. This library can be downloaded from here.
NTPClient.h and WiFiUdp.h are for NTP server synchronization and UDP protocol
handling respectively. The NTPClient library can be downloaded from here. The
WiFiUdp.h library is built-in, so there’s no need to install it.
Once the libraries are installed, copy and paste the following sketch into the Arduino
IDE, then upload it to the ESP8266:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#define DHTPin 2
#define DHTTYPE DHT22
DHT dht(DHTPin, DHTTYPE);
WiFiUDP ntpUDP;
const long utcOffsetInSeconds = 28800;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
unsigned long epochTime = timeClient.getEpochTime();
struct tm *ptm = gmtime ((time_t *)&epochTime);
ESP8266WebServer server(80);
float Temperature;
float Humidity;
String formattedTime;
String Date;
int Day;
int Month;
int Year;
void setup() {
Serial.begin(115200);
pinMode(DHTPin, INPUT);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);
server.begin();
dht.begin();
timeClient.begin();
}
void loop() {
server.handleClient();
void handle_OnConnect() {
timeClient.update();
formattedTime = timeClient.getFormattedTime();
Date = String(currentYear) + "-" + String(currentMonth) + "-" +
String(monthDay);
Temperature = dht.readTemperature();
Humidity = dht.readHumidity();
server.send(200, "text/html",
SendHTML(Temperature,Humidity,formattedTime,Date));
}
void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
ptr +="</head>\n";
ptr +="<body>\n";
ptr +="<div id=\"webpage\">\n";
ptr +="<h1>ESP8266 Global Server</h1>\n";
ptr +="</div>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DHT.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
Then, to connect to your home WiFi, enter your network credentials here:
UTC X = X * 60 * 60
I am in GMT+8 so for me,
UTC 8 = 8 * 60 * 60 = 28800
WiFiUDP ntpUDP;
const long utcOffsetInSeconds = 28800;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
The epoch time function returns the number of seconds that have elapsed since January
1, 1970. We use this function along with a time structure to get the date.
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);
server.begin();
dht.begin();
timeClient.begin();
}
Following the setup is the loop. The loop section only contains a single line. This line is a
function of the ESPWebserver library. It monitors the presence of a web client and
handles HTTP requests, just like POST and GET.
void loop() {
server.handleClient();
}
Inside the handle_OnConnect() function are the commands that fetch the current date,
time, temperature, and humidity readings from their respective libraries. Using the time
structure we set earlier, we get the current date. Whereas for time, we
use getFormattedTime() directly from the NTPClient library. Same goes for temperature
and humidity, where we use dht.readTemperature() and dht.readHumidity() directly
from the DHT library. Finally, server.send() returns the data to the client.
void handle_OnConnect() {
timeClient.update();
epochTime = timeClient.getEpochTime();
String Time = timeClient.getFormattedTime();
Time = timeClient.getFormattedTime();
Date = String(currentYear) + "-" + String(currentMonth) + "-" +
String(monthDay);
Temperature = dht.readTemperature();
Humidity = dht.readHumidity();
Last but not least, we use SendHTML() to create a web page according to the data we
have collected.
String SendHTML(float TemperatureWeb,float HumidityWeb, String TimeWeb,String
DateWeb){
String ptr = "<!DOCTYPE html> <html>\n";
ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-
scale=1.0, user-scalable=no\">\n";
ptr +="<title>ESP8266 Global Server</title>\n";
ptr +="</head>\n";
ptr +="<body>\n";
ptr +="<div id=\"webpage\">\n";
ptr +="<h1>ESP8266 Global Server</h1>\n";
ptr +="</div>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}
DEMONSTRATION
Upload the code to the ESP-01. Choose “Generic ESP8266 Module” as the board. Make
sure to select the correct port number as well.
After uploading, open the serial monitor and you should see something like this:
thingspeak
ThingSpeak is an Internet of Things (IoT) platform that allows users to
collect, analyze, and visualize data from connected devices. It was
developed by MathWorks, a software company that specializes in
mathematical computing.
Users can collect data from their devices and store it in channels, which are
like databases for the collected data. They can then use thingspeak’s built-
in tools to analyze and visualize the data in real-time, including plotting
graphs, creating charts, and generating maps.
Blynk is an Internet of Things (IoT) platform that provides a simple way for
developers to build IoT applications and connect them to the cloud. It was developed
by a startup based in Ukraine.
Blynk provides a mobile app that allows users to control their IoT devices remotely.
Users can create custom interfaces for their devices, such as buttons, sliders, and
graphs, and monitor data from sensors in real time. The app supports both iOS and
Android devices.
Blynk also provides a cloud service that allows developers to store and access data
from their IoT devices. The platform supports a wide range of microcontrollers and
development boards, such as Arduino, Raspberry Pi, ESP8266, and Particle, among
others.