Hello readers, I hope you all are doing great.
ESP32 is a powerful chip for Internet of Things applications. This tutorial is also based on one of the ESP32 applications in the field of IoT.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
In this tutorial, we will learn how to update LCD display with new data or input using a web server created with ESP32.
Fig. 1
To achieve the target, we will be using an HTML (Hypertext Markup Language) form to provide web input and then update the text displayed on LCD. The values or input received from the webserver will be further stored inside a variable in the code for further use (to display on LCD).
We have already posted a tutorial on LCD (Liquid Crystal Display) interfacing with ESP32. In that tutorial, we demonstrated how to display the hard-coded data (in the ESP32 module) on LCD.
A web server is computer software and hardware that accepts requests and responds to those requests using HTTP (Hypertext transfer protocol) or HTTPS (HTTP Secure) (HTTP is a network protocol for delivering online content to client user agents).
The ESP32 standalone web server is mobile-enabled and can be accessed from any device with a browser on the local network. B. Mobile phones, computers, laptops, tablets. However, all the devices must be connected to the same WiFi network to which the ESP32 is connected.
There are basically two ways to connect the ESP32 to a 16 * 2 LCD display.
Connecting an LCD display without an I2C adapter is cheap, but this method requires more connection cables and is complicated to implement. On the other hand, using an I2C adapter reduces complexity but increases cost. In this tutorial, you will connect the ESP32 directly without using an I2C adapter.
Table: 1
Fig. 2: ESP32 and 16*2 LCD interfacing
For more details on interfacing 16*2 LCD with ESP32, follow our previous tutorial at www.theengineeringprojects.com
We are using Arduino IDE to compile and upload code into ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.
We need to install two library files:
Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.
To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.
Fig. 3: adding necessary libraries
#include < WiFi.h >
#include < AsyncTCP.h >
#include < ESPAsyncWebServer.h >
#include < LiquidCrystal.h > // LCD header file
LiquidCrystal lcd (22, 23, 5, 18, 19, 21 );
AsyncWebServer server ( 80 );
// Enter your netwrok credentials
const char* ssid = "replace this with netwrok SSID";
const char* password = "replace this with Password";
const char* PARAM_INPUT_1 = "data_field1";
const char* PARAM_INPUT_2 = "data_field2";
// HTML web page to handle data input fields
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML> <html> <head>
<title> ESP Input Form </title>
<meta name = " viewport" content="width=device-width, initial-scale=1 ">
<style>
html{ font-family: Times New Roman; display: inline-block; text-align: justify;}
</style>
</head> <body>
<form action="/get">
Data_field1: <input type="text" name="data_field1" >
<input type="submit" value="Post ">
</form> <br>
<form action="/get">
Data_field2: <input type="text" name="data_field2">
<input type="submit" value="Post">
</form><br>
</body></html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
//===set LCD
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(1,0);
server.onNotFound(notFound);
server.begin();
// Send web page with input fields to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/html", index_html);
});
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
String inputParam;
// GET input1 value
if (request->hasParam(PARAM_INPUT_1))
{
inputMessage = request->getParam(PARAM_INPUT_1)->value();
inputParam = PARAM_INPUT_1;
}
// GET input2 value
else if (request->hasParam(PARAM_INPUT_2))
{
inputMessage = request->getParam(PARAM_INPUT_2)->value();
inputParam = PARAM_INPUT_2;
}
else
{
inputMessage = " No message sent";
inputParam = " none";
}
Serial.println ( inputMessage );
delay( 1000);
lcd.clear();
lcd.print( inputMessage);
request-> send (200, "text/html", " HTTP GET request sent to ESP32("
+ inputParam + "): " + inputMessage +
"<br><a href=\"/\"> Back to Home Page </a>");
});
}
void loop( )
{
}
Fig. 4: Adding header files
Fig. 5: LCD data and control pins
Fig. 6: server port
Fig. 7: Enter Network credentials
Fig. 8
Fig. 9: HTML web page
Fig. 10: HTML form for data input
Fig. 11: Post button.
Fig. 12
Fig. 13: Fetch/obtain the IP adrress
Fig. 14: Set 16*2 LCD
Fig. 15: Initialize the server
Fig. 16: Send web page to client
Fig. 17
Fig. read the input from HTML form
Fig. 18
Fig. 19
Fig. 20
Fig. 21: Select development board and COM port
Fig. 22: web Page
Fig. 23: Enter the Input to ESP32
Fig. 24: Input Updated
Fig. 25: IP address and Web Input on serial monitor.
Fig. 26: String input received from Web server, printed on LCD
This concludes the tutorial. We hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.
Hello readers, I hope you all are doing great. In this tutorial, we will learn how to update a webpage using Server-Sent Events and the ESP32 web server.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
It is a server push technology that enables the client devices to receive automatic updates from a server over HTTP (Hypertext Transfer Protocol) connection. SSE also describes how the server can initiate data transmission towards the client once an initial connection with the client has been established.
We have already posted a tutorial on how to implement Web socket protocol with ESP32 which is also a protocol used to notify events to a web client. Both the Server-Sent Events (SSE) and Web-Socket technologies seem to be quite similar but they are not.
The major difference between the two is that SSE is unidirectional, where the web client can only receive the updates from the ESP32 but it can’t send updates back to ESP32. On the other hand, the Web-socket protocol is bi-directional where both the web client and ESP32 can send and receive updates/events.
Fig. 1 Server-Sent event
The Server-Sent Event process initiates with an HTTP request from the web client or web page to the ESP32 web server. After that, the ESP32 is ready to send updates or events to the web client as they happen. But the web client can’t send any response or data to the ESP32 server after the initial handshake takes place.
Server-sent event technology can be used to communicate an event, GPIO states or to send sensor readings to the web client, whenever a new reading is observed.
For demonstration purpose, we are using a DHT11 sensor with the ESP32 module. ESP32 web server will display two things i.e., temperature and humidity observed using the DHT11 sensor. So, whenever a new reading is being observed, the ESP32 sends the reading to the Web Client over Server-sent events. After receiving the latest sensor reading the client updates the web page data.
Fig. 2 DHT11 sensor
DHT11 is a humidity and temperature sensor that measures its surrounding environment. It measures the temperature and humidity in a given area. It is made up of an NTC (negative temperature co-efficient) temperature sensor and a resistive humidity sensor. It also has an 8-bit microcontroller. The microcontroller is in charge of ADC (analog to digital conversion) and provides a digital output over the single wire protocol.
The DHT11 sensor can measure humidity from 20% to 90% with +-5 percent accuracy (RH or relative humidity) and temperature from 0 degrees Celsius to 50 degrees Celsius with +-2C accuracy.
DHT11 sensors can also be used to build a wired sensor network with a cable length of up to 20 meters.
Table 1
Note: Connect a 10K resistor between data and power (+5V) pin of DHT11 sensor module.
Fig. 3 ESP32 and DHT11 connections/wiring
We are using Arduino IDE to compile and upload code into the ESP32 module. You must have ESP32 board manager installed on your Arduino IDE to program the ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. The link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
Fig. 4 manage libraries
Fig. 5 Install DHT sensor library
ESP32 board manager doesn’t come with inbuilt libraries to create an asynchronous web server. So we need to download the library file from external sources and then add into Arduino IDE.
We need to install two library files:
Once you have successfully downloaded the required libraries, next step it to install or add these libraries in Arduino IDE.
To add the libraries in Arduino IDE, go to Sketch >> Include Library >> Add .zip library and then select the downloaded library files.
Fig. 6 adding necessary libraries
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
// Replace with your network credentials
const char* ssid = "SSID";
const char* password = "password";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create an Event Source on /events
AsyncEventSource events("/events");
// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 20000; //20 sec timer delay
//==== Creating web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<title>SSE with ESP32 Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="icon" href="data:,">
<style>
html {font-family: Times New Roman; display: inline-block; text-align: justify;}
p { font-size: 1.2rem;}
body { margin: 0;}
.topnav { overflow: hidden; background-color: blue; color: white; font-size: 1rem; }
.content { padding: 20px; }
.card { background-color: #ADD8E6; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); }
.cards { max-width: 600px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.reading { font-size: 1.4rem; }
</style>
</head>
<body>
<div class="topnav">
<h1>Server-Sent Events </h1>
<h2> DHT11 Sensor Data </h2>
</div>
<div class="content">
<div class="cards">
<div class="card">
<p> DHT11 Temperature</p><p><span class="reading"><span id="temp">%TEMPERATURE%</span> °C</span></p>
</div>
<div class="card">
<p> DHT11 Humidity</p><p><span class="reading"><span id="hum">%HUMIDITY%</span> %</span></p>
</div>
</div>
</div>
<script>
if (!!window.EventSource)
{
var source = new EventSource('/events');
source.addEventListener('open', function(e)
{
console.log("Events Connected");
}, false);
source.addEventListener('error', function(e)
{
if (e.target.readyState != EventSource.OPEN)
{
console.log("Events Disconnected");
}
}, false);
source.addEventListener('message', function(e)
{
console.log("message", e.data);
}, false);
source.addEventListener('temperature', function(e)
{
console.log("temperature", e.data);
document.getElementById("temp").innerHTML = e.data;
}, false);
source.addEventListener('humidity', function(e)
{
console.log("humidity", e.data);
document.getElementById("hum").innerHTML = e.data;
}, false);
}
</script>
</body>
</html>)rawliteral";
void setup() {
Serial.begin(115200); //initialize serial monitor
//===set and initialize Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.print("IP Address: ");
Serial.println(WiFi.localIP()); // print the IP address
//====Initialize DHT11 sensor
dht.begin();
//====Handle Web Server
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Handle Web Server Events
events.onConnect([](AsyncEventSourceClient *client)
{
if(client->lastId())
{
Serial.printf("Client reconnected! Last message ID that it got is: %u\n",
client->lastId());
}
// send event with message "hello!", id current millis
// and set reconnect delay to 1 second
client->send("hello!", NULL, millis(), 10000);
});
server.addHandler(&events);
server.begin();
}
void loop()
{
delay(2000);
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
if ((millis() - lastTime) > timerDelay)
{
// Send Events to the Web Server with the Sensor Readings
events.send("ping",NULL,millis());
events.send(String(temperature).c_str(),"temperature",millis());
events.send(String(humidity).c_str(),"humidity",millis());
Serial.print(F("Humidity(%): "));
Serial.println(humidity);
Serial.print(F("Temp.: "));
Serial.print(temperature);
Serial.println(F("°C "));
}
}
Fig. 7 Header files
Fig. 8 Global declarations
Fig. 9
Fig. 10 Enter Network credentials
Fig. 11 Server port
Fig. 12 Event source
Fig. 13 Timer Variables
Fig. 14
Fig. 15
Fig. 16
Fig. 17
Fig. 18
Fig. 19
Fig. 20
Fig. 21 Fetch/obtain the IP address
Fig. 22 Initialize DHT sensor
Fig. 23
Fig. 24 Handling server events
Fig. 24 initializing web server
Fig. 25
Fig. 26 If error occurs while reading data from DHT11
Fig. 27 Sending events to the server
Fig. 28 Print Sensor data on the Serial monitor
Fig. 29 Select development board and COM port
Fig. 30
Fig. 31
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with a new tutorial on ESP32.