ESP8266 Data Logger to Upload Data on Webserver
Today we will learn to build NodeMCU ESP8266 Data Logger to Upload Data on Webserver. You often have seen the data logging projects with real-time graphs and tables using IoT Platforms like ThingSpeak. But today in this session we will learn to create own web server and update the data in realtime. We have already created many data logging projects on a webserver using different ESP boards.
Here we will create NodeMCU ESP8266 Data Logger using DHT11 Sensor, while Temperature and Humidity will be uploaded on Web Server using Ajax.
Components Required
The followings are the components required for making ESP8266 based Data Logger on Web server.
- NodeMCU ESP8266
- DHT11 Sensor
- Jumper Wires
DHT11 sensor is used to measure temperature and humidity of surroundings. It is also generally used to create weather stations.
Circuit Diagram of ESP8266 Data Logger
The Circuit Diagram for ESP8266 Data Logger to Upload Data on Webserver is given below:
Also, Read: Secure HTTPS Requests to URL Using NodeMCU ESP8266
The wiring of the DHT11 sensor to the NodeMCU (ESP8266) is very easy. VCC and GND pins of DHT11 is connected to 3.3V and GND of NodeMCU while the Data pin of DHT is connected to D1 (GPIO 05) pin of NodeMCU.
You can use any other suitable GPIO pins. But, If you’re using an ESP-01, GPIO 2 is the most suitable pin to interface to the DHT11 sensor data pin.
Programming NodeMCU ESP8266 for Data logging
Complete code for NodeMCU and DHT11 (Temperature and Humidity sensor) Data Logger can be found at the end of this tutorial. Here I’m explaining the complete code in a step by step manner:
Before moving on to the coding part, you need to install the required libraries. The ESP8266 libraries are pre-installed on IDE while installing ESP8266 Board Manager. But, if this is your first time on coding NodeMCU, Follow this guide to Install ESP8266 Board Manager.
Now, install the DHT11 library file that can download from below:
After installing the library file, including all the required libraries header file.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "DHT.h"
Now in the next lines, enter your Wi-Fi Network Credentials like: SSID and Password.
const char* ssid = "Wi-Fi Name";
const char* password = "Password";
Now, define the type of DHT sensor used and the data pin where the sensor is connected. If you are using DHT22 Sensor, then change the DHT type to DHT22. For the Demonstration, the DHT sensor is connected to the GPIO5 (D1) of NodeMCU.
#define LED 2 //Onboard LED
#define DHTTYPE DHT11 // DHT 11
uint8_t DHTPin = 5;
DHT dht(DHTPin, DHTTYPE);
The handleRoot function is initiated when we open the Webpage in the browser using the NodeMCU ESP8266 IP address.
void handleRoot()
{
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}
The next function, readData() is used to grab the data from the DHT11 sensor and send it to the Webpage. In this loop, ESP8266 stores the DHT11 values into two different float variables: temperature & humidity. After that, it converts those float variables into the string and stores their data into another string variable called ‘Data’. Finally, It is sent to the Webpage whenever requested.
void readData()
{
String data = "{"Temperature":""+ String(temperature) +"", "Humidity":""+ String(humidity) +""}";
digitalWrite(LED,!digitalRead(LED));
server.send(200, "text/plane", data);
delay(2000);
temperature = dht.readTemperature();
humidity = dht.readHumidity();
Serial.print(humidity, 1);
Serial.print(temperature, 1);
}
Inside the void setup() function, we initialized the baud rate for serial Monitor. Similarly, Using .begin() function, connect the module with the Wi-Fi using the Wi-Fi SSID and password.
Serial.begin(115200);
pinMode(DHTPin, INPUT);
dht.begin();
WiFi.begin(ssid, password);
server.begin();
Firstly, we call the ‘handleRoot‘ function when a client requests URI (Uniform Resource Identifier) “/”. Secondly, we call the ‘readData‘ function when a POST request is made to URI “/readData“
server.on("/", handleRoot);
server.on("/readData", readData);
In void loop() function we continuously check for HTTP requests from clients
void loop(void)
{
server.handleClient();
}
HTML Code for ESP Data Logger Web page
The <!DOCTYPE html > tag is used to tell the web browser that which version of html we are using to program Web Page. Basically, this tag is written at the top. Everything, that in this code is written after <!DOCTYPE html >
<!doctype html>
The code written between the <html> </html> tags will be read by the browser. Similarly, the <head> </head> tag is used to define the title, header line, and style the web page. The data written in the <title></title> is displayed on the tab of the browser. Again, the <style></style> tag is used to style the table and the header lines.
<html>
<head>
<title>Data Logger</title>
<h1 style="text-align:center; color:red;">Iot Design Pro</h1>
<style>
canvas{
-moz-user-select: none;
……………………..
……………………..
……………………..
</style>
</head>
The <script></script> tag is used to include the jQuery. jQuery is nothing but the JavaScript library. The getData() function in the <script> tag is used to take the data from ESP8266 and update the data table.
function getData()
{
…………..
…………..
The XMLHttpRequest object is used to call data from the webserver. All browsers have a built-in XMLHttpRequest object to call data from a server. Using the XMLHttpRequest, we can update a web page without reloading it, request data, receive data, and can send data to a server. Here we are using this object to get the temperature and humidity data from the DHT11 Sensor and NodeMCU and update the data on the table without refreshing the web page.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Push the data in array
var time = new Date().toLocaleTimeString();
var txt = this.responseText;
var obj = JSON.parse(txt);
Tvalues.push(obj.Temperature);
Hvalues.push(obj.Humidity);
timeStamp.push(time);
……………………….
…………….................
……………………….
The open() and send() methods of the XMLHttpRequest object are used to send a request to a web server. The syntax for xhttp.open() is provided below:
xhttp.open(method, url, async)
Where:
method is the type ofrequest (GET or POST)
url is the server location
async is used to define asynchronous or synchronous, where true is asynchronous and false is synchronous
xhttp.open("GET", "readData", true);
xhttp.send();
ESP8266 Data Logger Source Code
The complete Program code for ESP8266 Data Logger is provided below.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "DHT.h"
#ifndef STASSID
#define STASSID "Alsan Air WiFi 4"
#define STAPSK "11122235122@kap"
#endif
const char *ssid = STASSID;
const char *password = STAPSK;
#define LED 2 //On board LED
#define DHTTYPE DHT11 // DHT 11
uint8_t DHTPin = 5;
DHT dht(DHTPin, DHTTYPE);
float humidity, temperature;
ESP8266WebServer server(80);
const char MAIN_page[] PROGMEM = R"=====(
<!doctype html>
<html>
<head>
<title>Data Logger</title>
<h1 style="text-align:center; color:red;">The IoT Projects</h1>
<h3 style="text-align:center;">ESP8266 Data Logger</h3>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
/* Data Table Styling*/
#dataTable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
text-align: center;
}
#dataTable td, #dataTable th {
border: 1px solid #ddd;
padding: 8px;
}
#dataTable tr:nth-child(even){background-color: #f2f2f2;}
#dataTable tr:hover {background-color: #ddd;}
#dataTable th {
padding-top: 12px;
padding-bottom: 12px;
text-align: center;
background-color: #050505;
color: white;
}
</style>
</head>
<body>
<div>
<table id="dataTable">
<tr><th>Time</th><th>Temperaure (°C)</th><th>Humidity (%)</th></tr>
</table>
</div>
<br>
<br>
<script>
var Tvalues = [];
var Hvalues = [];
var timeStamp = [];
setInterval(function() {
// Call a function repetatively with 5 Second interval
getData();
}, 5000); //5000mSeconds update rate
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Push the data in array
var time = new Date().toLocaleTimeString();
var txt = this.responseText;
var obj = JSON.parse(txt);
Tvalues.push(obj.Temperature);
Hvalues.push(obj.Humidity);
timeStamp.push(time);
//Update Data Table
var table = document.getElementById("dataTable");
var row = table.insertRow(1); //Add after headings
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = time;
cell2.innerHTML = obj.Temperature;
cell3.innerHTML = obj.Humidity;
}
};
xhttp.open("GET", "readData", true); //Handle readData server on ESP8266
xhttp.send();
}
</script>
</body>
</html>
)=====";
void handleRoot()
{
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}
void readData()
{
String data = "{"Temperature":""+ String(temperature) +"", "Humidity":""+ String(humidity) +""}";
digitalWrite(LED,!digitalRead(LED));
server.send(200, "text/plane", data);
delay(2000);
temperature = dht.readTemperature();
humidity = dht.readHumidity();
Serial.print(humidity, 1);
Serial.print(temperature, 1);
}
void setup(void) {
Serial.begin(115200);
pinMode(DHTPin, INPUT);
dht.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/readData", readData);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
MDNS.update();
}
Demonstration of NodeMCU Data Logger
Finally, connect the DHT11 sensor with NodeMCU and upload the code. After uploading the program in NodeMCU, open serial monitor with 115200 baud rate and get the IP address of NodeMCU. Open it in the web browser, and your Webpage will look like this:
Conclusion
Finally, we have completed the NodeMCU ESP8266 Data Logger to Upload Data on Webserver. I hope you found this project useful! Drop a comment below if you have any doubts or queries. I’ll do my best to answer your questions.
Our Previous Post:
- ESP8266 based Coronavirus Tracker for your country
- BME280 Based Mini Weather Station using ESP8266/ESP32
- Simple Weather station using Arduino & BME280 Barometric Pressure Sensor
- Temperature Controlled Home Automation using Arduino
- Connect RFID to PHP & MySQL Database with NodeMcu ESP8266
- IoT Based RFID Attendance System using ESP32
- Capacitive Soil Moisture Sensor with OLED Display & Arduino
- Insert Data into MySQL Database with ESP8266 Development Board
- Contactless Smart Doorbell Using ESP8266 & Blynk
- Home Automation with ESP8266 Web Server & Relay Module Control Appliances from Local Network
- IoT based Silent Intruder Alarm using Arduino