This project shows how to build a web server with the ESP32 to plot sensor readings in charts with multiple series. As an example, we’ll plot sensor readings from four different DS18B20 temperature sensors on the same chart. You can modify the project to plot any other data. To build the charts, we’ll use the Highcharts JavaScript library.

We have a similar tutorial for the ESP8266 NodeMCU board:
This project will build a web server with the ESP32 that displays temperature readings from four DS18B20 temperature sensors on the same chart—chart with multiple series. The chart displays a maximum of 40 data points for each series, and new readings are added every 30 seconds. You can change these values in your code.

The DS18B20 temperature sensor is a one-wire digital temperature sensor. This means that it just requires one data line to communicate with your microcontroller.

Each sensor has a unique 64-bit serial number, which means you can connect multiple sensors to the same GPIO—as we’ll do in this tutorial. Learn more about the DS18B20 temperature sensor:
The readings are updated automatically on the web page using Server-Sent Events (SSE).

To learn more about SSE, you can read:
To keep our project better organized and easier to understand, we’ll save the HTML, CSS, and JavaScript files to build the web page on the board’s filesystem (LittleFS).
Make sure you check all the prerequisites in this section before continuing with the project.
We’ll program the ESP32 using Arduino IDE. So, you must have the ESP32 add-on installed. Follow the next tutorial if you haven’t already:
If you want to use VS Code with the PlatformIO extension, follow the next tutorial instead to learn how to program the ESP32:
To upload the HTML, CSS, and JavaScript files to the ESP32 flash memory (LittleFS), we’ll use a plugin for Arduino IDE: LittleFS Filesystem uploader. Follow the next tutorial to install the filesystem uploader plugin:
If you’re using VS Code with the PlatformIO extension, read the following tutorial to learn how to upload files to the filesystem:
To build this project, you need to install the following libraries:
You can install the libraries using the Arduino Library Manager. Go to Sketch > Include Library > Manage Libraries and search for the libraries’ names.
To follow this tutorial you need the following parts:
If you don’t have four DS18B20 sensors, you can use three or two. Alternatively, you can also use other sensors (you need to modify the code) or data from any other source (for example, sensor readings received via MQTT, ESP-NOW, or random values—to experiment with this project…)
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Wire four DS18B20 sensors to your board.

Recommended reading: ESP32 Pinout Reference: Which GPIO pins should you use?
Each DS18B20 temperature sensor has an assigned serial number. First, you need to find that number to label each sensor accordingly. You need to do this so that later you know from which sensor you’re reading the temperature.
Upload the following code to the ESP32. Make sure you have the right board and COM port selected.
/* * Rui Santos * Complete Project Details https://randomnerdtutorials.com */ #include <OneWire.h> // Based on the OneWire library example OneWire ds(4); //data wire connected to GPIO 4 void setup(void) { Serial.begin(115200); } void loop(void) { byte i; byte addr[8]; if (!ds.search(addr)) { Serial.println(" No more addresses."); Serial.println(); ds.reset_search(); delay(250); return; } Serial.print(" ROM ="); for (i = 0; i < 8; i++) { Serial.write(' '); Serial.print(addr[i], HEX); } }
Wire just one sensor at a time to find its address (or successively add a new sensor) so that you’re able to identify each one by its address. Then, you can add a physical label to each sensor.
Open the Serial Monitor at a baud rate of 115200, press the on-board RST/EN button and you should get something as follows (but with different addresses):

Untick the “Autoscroll” option so that you’re able to copy the addresses. In our case, we’ve got the following addresses:
To keep the project organized and make it easier to understand, we’ll create four files to build the web server:
You should save the HTML, CSS, and JavaScript files inside a folder called data inside the Arduino sketch folder, as shown in the previous diagram. We’ll upload these files to the ESP32 filesystem (LittleFS).
You can download all project files:
Copy the following to the index.html file.
<!-- Complete project details: https://randomnerdtutorials.com/esp32-plot-readings-charts-multiple/ --> <!DOCTYPE html> <html> <head> <title>ESP IOT DASHBOARD</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="favicon.png"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://code.highcharts.com/highcharts.js"></script> </head> <body> <div class="topnav"> <h1>ESP WEB SERVER CHARTS</h1> </div> <div class="content"> <div class="card-grid"> <div class="card"> <p class="card-title">Temperature Chart</p> <div id="chart-temperature" class="chart-container"></div> </div> </div> </div> <script src="script.js"></script> </body> </html>
The HTML file for this project is very simple. It includes the JavaScript Highcharts library in the head of the HTML file:
<script src="https://code.highcharts.com/highcharts.js"></script>
There is a <div> section with the id chart-temperature where we’ll render our chart later on.
<div id="chart-temperature" class="chart-container"></div>
Copy the following styles to your style.css file.
/* Complete project details: https://randomnerdtutorials.com/esp32-plot-readings-charts-multiple/ */ html { font-family: Arial, Helvetica, sans-serif; display: inline-block; text-align: center; } h1 { font-size: 1.8rem; color: white; } p { font-size: 1.4rem; } .topnav { overflow: hidden; background-color: #0A1128; } body { margin: 0; } .content { padding: 5%; } .card-grid { max-width: 1200px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); } .card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); } .card-title { font-size: 1.2rem; font-weight: bold; color: #034078 } .chart-container { padding-right: 5%; padding-left: 5%; }
Copy the following to the script.js file. Here’s a list of what this code does:
// Complete project details: https://randomnerdtutorials.com/esp32-plot-readings-charts-multiple/ // Get current sensor readings when the page loads window.addEventListener('load', getReadings); // Create Temperature Chart var chartT = new Highcharts.Chart({ chart:{ renderTo:'chart-temperature' }, series: [ { name: 'Temperature #1', type: 'line', color: '#101D42', marker: { symbol: 'circle', radius: 3, fillColor: '#101D42', } }, { name: 'Temperature #2', type: 'line', color: '#00A6A6', marker: { symbol: 'square', radius: 3, fillColor: '#00A6A6', } }, { name: 'Temperature #3', type: 'line', color: '#8B2635', marker: { symbol: 'triangle', radius: 3, fillColor: '#8B2635', } }, { name: 'Temperature #4', type: 'line', color: '#71B48D', marker: { symbol: 'triangle-down', radius: 3, fillColor: '#71B48D', } }, ], title: { text: undefined }, xAxis: { type: 'datetime', dateTimeLabelFormats: { second: '%H:%M:%S' } }, yAxis: { title: { text: 'Temperature Celsius Degrees' } }, credits: { enabled: false } }); //Plot temperature in the temperature chart function plotTemperature(jsonValue) { var keys = Object.keys(jsonValue); console.log(keys); console.log(keys.length); for (var i = 0; i < keys.length; i++){ var x = (new Date()).getTime(); console.log(x); const key = keys[i]; var y = Number(jsonValue[key]); console.log(y); if(chartT.series[i].data.length > 40) { chartT.series[i].addPoint([x, y], true, true, true); } else { chartT.series[i].addPoint([x, y], true, false, true); } } } // Function to get current readings on the webpage when it loads for the first time function getReadings(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); console.log(myObj); plotTemperature(myObj); } }; xhr.open("GET", "/readings", true); xhr.send(); } 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('new_readings', function(e) { console.log("new_readings", e.data); var myObj = JSON.parse(e.data); console.log(myObj); plotTemperature(myObj); }, false); }
When you access the web page for the first time, we’ll request the server to get the current sensor readings. Otherwise, we would have to wait for new sensor readings to arrive (via Server-Sent Events), which can take some time depending on the interval that you set on the server.
Add an event listener that calls the getReadings function when the web page loads.
// Get current sensor readings when the page loads window.addEventListener('load', getReadings);
The window object represents an open window in a browser. The addEventListener() method sets up a function to be called when a certain event happens. In this case, we’ll call the getReadings function when the page loads (‘load’) to get the current sensor readings.
Now, let’s take a look at the getReadings function. Create a new XMLHttpRequest object. Then, send a GET request to the server on the /readings URL using the open() and send() methods.
function getReadings() { var xhr = new XMLHttpRequest(); xhr.open("GET", "/readings", true); xhr.send(); }
When we send that request, the ESP will send a response with the required information. So, we need to handle what happens when we receive the response. We’ll use the onreadystatechange property that defines a function to be executed when the readyState property changes. The readyState property holds the status of the XMLHttpRequest. The response of the request is ready when the readyState is 4, and the status is 200.
So, the request should look something like this:
function getStates(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { … DO WHATEVER YOU WANT WITH THE RESPONSE … } }; xhr.open("GET", "/states", true); xhr.send(); }
The response sent by the ESP is the following text in JSON format.
{ "sensor1" : "25", "sensor2" : "21", "sensor3" : "22", "sensor4" : "23" }
We need to convert the JSON string into a JSON object using the parse() method. The result is saved on the myObj variable.
var myObj = JSON.parse(this.responseText);
The myObj varible is a JSON object that contains all the temperature readings. We want to plot those readings on the same chart. For that, we’ve created a function called plotTemperature() that plots the temperatures stored in a JSON object on a chart.
plotTemperature(myObj);
Here’s the complete getReadings() function.
function getReadings(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); console.log(myObj); plotTemperature(myObj); } }; xhr.open("GET", "/readings", true); xhr.send(); }
The following lines create the charts with multiple series.
// Create Temperature Chart var chartT = new Highcharts.Chart({ chart:{ renderTo:'chart-temperature' }, series: [ { name: 'Temperature #1', type: 'line', color: '#101D42', marker: { symbol: 'circle', radius: 3, fillColor: '#101D42', } }, { name: 'Temperature #2', type: 'line', color: '#00A6A6', marker: { symbol: 'square', radius: 3, fillColor: '#00A6A6', } }, { name: 'Temperature #3', type: 'line', color: '#8B2635', marker: { symbol: 'triangle', radius: 3, fillColor: '#8B2635', } }, { name: 'Temperature #4', type: 'line', color: '#71B48D', marker: { symbol: 'triangle-down', radius: 3, fillColor: '#71B48D', } }, ], title: { text: undefined }, xAxis: { type: 'datetime', dateTimeLabelFormats: { second: '%H:%M:%S' } }, yAxis: { title: { text: 'Temperature Celsius Degrees' } }, credits: { enabled: false } });
To create a new chart, use the new Highcharts.Chart() method and pass as argument the chart properties.
var chartT = new Highcharts.Chart({
In the next line, define where you want to put the chart. In our example, we want to place it in the HTML element with the chart-temperature id—see the HTML file section.
chart:{ renderTo:'chart-temperature' },
Then, define the options for the series. The following lines create the first series:
series: [ { name: 'Temperature #1', type: 'line', color: '#101D42', marker: { symbol: 'circle', radius: 3, fillColor: '#101D42', }
The name property defines the series name. The type property defines the type of chart—in this case, we want to build a line chart. The color refers to the color of the line—you can change it to whatever color you desire.
Next, define the marker properties. You can choose from several default symbols—square, circle, diamond, triangle, triangle-down. You can also create your own symbols. The radius refers to the size of the marker, and the fillColor refers to the color of the marker. There are other properties you can use to customize the marker—learn more.
marker: { symbol: 'circle', radius: 3, fillColor: '#101D42', }
Creating the other series is similar, but we’ve chosen different names, markers and colors.
There are many other options you can use to customize your series—check the documentation about plotOptions.
You can also define the chart title—in this case, as we’ve already defined a title for the chart in a heading of the HTML file, we will not set the title here. The title is displayed by default, so we must set it to undefined.
title: { text: undefined },
Define the properties for the X axis—this is the axis where we’ll display data and time. Check more options to customize the X axis.
xAxis: { type: 'datetime', dateTimeLabelFormats: { second: '%H:%M:%S' } },
We set the title for the y axis. See all available properties for the y axis.
yAxis: { title: { text: 'Temperature Celsius Degrees' } }
If, for some reason, after building the project, the charts are not showing the right time zone, add the following lines to the JavaScript file after the second line:
Highcharts.setOptions({ time: { timezoneOffset: -60 //Add your time zone offset here in minutes } });
The charts will show the time in UTC. If you want it to display in your timezone, you must set the useUTC parameter (which is a time parameter) as false:
time:{ useUTC: false },
So, add that when creating the chart as follows:
var chart = new Highcharts.Chart({ time:{ useUTC: false }, (…)
To learn more about this property, check this link on the documentation: https://api.highcharts.com/highcharts/time.useUTC
Finally, set the credits option to false to hide the credits of the Highcharts library.
credits: { enabled: false }
We’ve created the plotTemperature() function that accepts as an argument a JSON object with the temperature readings we want to plot.
//Plot temperature in the temperature chart function plotTemperature(jsonValue) { var keys = Object.keys(jsonValue); console.log(keys); console.log(keys.length); for (var i = 0; i < keys.length; i++){ var x = (new Date()).getTime(); console.log(x); const key = keys[i]; var y = Number(jsonValue[key]); console.log(y); if(chartT.series[i].data.length > 40) { chartT.series[i].addPoint([x, y], true, true, true); } else { chartT.series[i].addPoint([x, y], true, false, true); } } }
First, we get the keys of our JSON object and save them on the keys variable. This allows us to go through all the keys in the object.
var keys = Object.keys(jsonValue);
The keys variable will be an array with all the keys in the JSON object. In our case:
["sensor1", "sensor2", "sensor3", "sensor4"]
This works if you have a JSON object with a different number of keys or with different keys. Then, we’ll go through all the keys (keys.length()) to plot each of its value in the chart.
The x value for the chart is the timestamp.
var x = (new Date()).getTime()
The key variable holds the current key in the loop. The first time we go through the loop, the key variable is “sensor1”.
const key = keys[i];
Then, we get the value of the key (jsonValue[key]) and save it as a number in the y variable.
Our chart has multiple series (index starts at 0). We can access the first series in the
temperature chart using: chartT.series[0], which corresponds to chartT.series[i] the first time we go through the loop.
First, we check the series data length:
To add a new point use the addPoint() method that accepts the following arguments:
So, to add a point to the chart, we use the next lines:
if(chartT.series[i].data.length > 40) { chartT.series[i].addPoint([x, y], true, true, true); } else { chartT.series[i].addPoint([x, y], true, false, true); }
Plot the readings on the charts when the client receives the readings on the new_readings event.
Create a new EventSource object and specify the URL of the page sending the updates. In our case, it’s /events.
if (!!window.EventSource) { var source = new EventSource('/events');
Once you’ve instantiated an event source, you can start listening for messages from the server with addEventListener().
These are the default event listeners, as shown here in the AsyncWebServer documentation.
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);
Then, add the event listener for new_readings.
source.addEventListener('new_readings', function(e) {
When new readings are available, the ESP32 sends an event (new_readings) to the client. The following lines handle what happens when the browser receives that event.
source.addEventListener('new_readings', function(e) { console.log("new_readings", e.data); var myObj = JSON.parse(e.data); console.log(myObj); plotTemperature(myObj); }, false);
Basically, print the new readings on the browser console, convert the data into a JSON object and plot the readings on the chart by calling the plotTemperature() function.
Copy the following code to your Arduino IDE or to the main.cpp file if you’re using PlatformIO.
/********* Rui Santos & Sara Santos - Random Nerd Tutorials Complete instructions at https://RandomNerdTutorials.com/esp32-plot-readings-charts-multiple/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. *********/ #include <Arduino.h> #include <WiFi.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include "LittleFS.h" #include <Arduino_JSON.h> #include <OneWire.h> #include <DallasTemperature.h> // Replace with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); // Create an Event Source on /events AsyncEventSource events("/events"); // Json Variable to Hold Sensor Readings JSONVar readings; // Timer variables unsigned long lastTime = 0; unsigned long timerDelay = 30000; // GPIO where the DS18B20 sensors are connected to const int oneWireBus = 4; // Setup a oneWire instance to communicate with OneWire devices (DS18B20) OneWire oneWire(oneWireBus); // Pass our oneWire reference to Dallas Temperature sensor DallasTemperature sensors(&oneWire); // Address of each sensor DeviceAddress sensor3 = { 0x28, 0xFF, 0xA0, 0x11, 0x33, 0x17, 0x3, 0x96 }; DeviceAddress sensor1 = { 0x28, 0xFF, 0xB4, 0x6, 0x33, 0x17, 0x3, 0x4B }; DeviceAddress sensor2 = { 0x28, 0xFF, 0x43, 0xF5, 0x32, 0x18, 0x2, 0xA8 }; DeviceAddress sensor4 = { 0x28, 0xFF, 0x11, 0x28, 0x33, 0x18, 0x1, 0x6B }; // Get Sensor Readings and return JSON object String getSensorReadings(){ sensors.requestTemperatures(); readings["sensor1"] = String(sensors.getTempC(sensor1)); readings["sensor2"] = String(sensors.getTempC(sensor2)); readings["sensor3"] = String(sensors.getTempC(sensor3)); readings["sensor4"] = String(sensors.getTempC(sensor4)); String jsonString = JSON.stringify(readings); return jsonString; } // Initialize LittleFS void initLittleFS() { if (!LittleFS.begin()) { Serial.println("An error has occurred while mounting LittleFS"); } else{ Serial.println("LittleFS mounted successfully"); } } // Initialize WiFi void initWiFi() { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println(WiFi.localIP()); } void setup() { // Serial port for debugging purposes Serial.begin(115200); initWiFi(); initLittleFS(); // Web Server Root URL server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(LittleFS, "/index.html", "text/html"); }); server.serveStatic("/", LittleFS, "/"); // Request for the latest sensor readings server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){ String json = getSensorReadings(); request->send(200, "application/json", json); json = String(); }); 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); // Start server server.begin(); } void loop() { if ((millis() - lastTime) > timerDelay) { // Send Events to the client with the Sensor Readings Every 10 seconds events.send("ping",NULL,millis()); events.send(getSensorReadings().c_str(),"new_readings" ,millis()); lastTime = millis(); } }
Let’s take a look at the code and see how it works to send readings to the client using server-sent events.
The OneWire and DallasTemperature libraries are needed to interface with the DS18B20 temperature sensors.
#include <OneWire.h> #include <DallasTemperature.h>
The WiFi, ESPAsyncWebServer and AsyncTCP libraries are used to create the web server.
#include <Arduino.h> #include <WiFi.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h>
The HTML, CSS, and JavaScript files to build the web page are saved on the ESP32 filesystem (LittleFS). So, we also need to include the LittleFS library.
#include "LittleFS.h"You also need to include the Arduino_JSON library to make it easier to handle JSON strings.
#include <Arduino_JSON.h>Insert your network credentials in the following variables, so that the ESP32 can connect to your local network using Wi-Fi.
const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Create an AsyncWebServer object on port 80.
AsyncWebServer server(80);
The following line creates a new event source on /events.
AsyncEventSource events("/events");
The readings variable is a JSON variable to hold the sensor readings in JSON format.
JSONVar readings;The lastTime and the timerDelay variables will be used to update sensor readings every X number of seconds. As an example, we’ll get new sensor readings every 30 seconds (30000 milliseconds). You can change that delay time in the timerDelay variable.
// Timer variables unsigned long lastTime = 0; unsigned long timerDelay = 30000;
The DS18B20 temperature sensors are connected to GPIO 4.
// GPIO where the DS18B20 sensors are connected to const int oneWireBus = 4;
Setup a oneWire instance to communicate with OneWire devices (DS18B20):
OneWire oneWire(oneWireBus);
Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
Insert the addresses of your DS18B20 Sensors in the following lines (check this section if you don’t have the addresses of your sensors):
// Address of each sensor DeviceAddress sensor3 = { 0x28, 0xFF, 0xA0, 0x11, 0x33, 0x17, 0x3, 0x96 }; DeviceAddress sensor1 = { 0x28, 0xFF, 0xB4, 0x6, 0x33, 0x17, 0x3, 0x4B }; DeviceAddress sensor2 = { 0x28, 0xFF, 0x43, 0xF5, 0x32, 0x18, 0x2, 0xA8 }; DeviceAddress sensor4 = { 0x28, 0xFF, 0x11, 0x28, 0x33, 0x18, 0x1, 0x6B };
To get readings from the DS18B20 temperature sensors, first, you need to call the requesTemperatures() method on the sensors object. Then, use the getTempC() function and pass as argument the address of the sensor you want to get the temperature—this gets the temperature in celsius degrees.
Note: if you want to get the temperature in Fahrenheit degrees, use the getTemF() function instead.
Finally, save the readings in a JSON string (jsonString variable) and return that variable.
// Get Sensor Readings and return JSON object String getSensorReadings(){ sensors.requestTemperatures(); readings["sensor1"] = String(sensors.getTempC(sensor1)); readings["sensor2"] = String(sensors.getTempC(sensor2)); readings["sensor3"] = String(sensors.getTempC(sensor3)); readings["sensor4"] = String(sensors.getTempC(sensor4)); String jsonString = JSON.stringify(readings); return jsonString; }
The initLittleFS() function initializes the LittleFS filesystem:
// Initialize LittleFS void initLittleFS() { if (!LittleFS.begin()) { Serial.println("An error has occurred while mounting LittleFS"); } else{ Serial.println("LittleFSmounted successfully"); } }
The initWiFi() function initializes Wi-Fi and prints the IP address on the Serial Monitor.
// Initialize WiFi void initWiFi() { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println(WiFi.localIP()); }
In the setup(), initialize the Serial Monitor, Wi-Fi and filesystem.
Serial.begin(115200); initWiFi(); initLittleFS();
When you access the ESP32 IP address on the root / URL, send the text that is stored on the index.html file to build the web page.
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(LittleFS, "/index.html", "text/html"); });
Serve the other static files requested by the client (style.css and script.js).
server.serveStatic("/", LittleFS, "/");
Send the JSON string with the current sensor readings when you receive a request on the /readings URL.
// Request for the latest sensor readings server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){ String json = getSensorReadings(); request->send(200, "application/json", json); json = String(); });
The json variable holds the return from the getSensorReadings() function. To send a JSON string as response, the send() method accepts as first argument the response code (200), the second is the content type (“application/json”) and finally the content (json variable).
Set up the event source on the server.
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);
Finally, start the server.
server.begin();
In the loop(), send events to the browser with the newest sensor readings to update the web page every 30 seconds.
if ((millis() - lastTime) > timerDelay) { // Send Events to the client with the Sensor Readings Every 10 seconds events.send("ping",NULL,millis()); events.send(getSensorReadings().c_str(),"new_readings" ,millis()); lastTime = millis(); }
Use the send() method on the events object and pass as an argument the content you want to send and the name of the event. In this case, we want to send the JSON string returned by the getSensorReadings() function. The name of the events is new_readings.
After inserting your network credentials, save the code. Go to Sketch > Show Sketch Folder, and create a folder called data.

Inside that folder you should save the HTML, CSS and JavaScript files.
Then, upload the code to your ESP32 board. Make sure you have the right board and COM port selected. Also, make sure you’ve added your networks credentials and the sensors’ addresses to the code.
After uploading the code, you need to upload the files to the filesystem.
Press [Ctrl] + [Shift] + [P] on Windows or [⌘] + [Shift] + [P] on MacOS to open the command palette. Search for the Upload LittleFS to Pico/ESP8266/ESP32 command and click on it.
If you don’t have this option is because you didn’t install the filesystem uploader plugin. Check this tutorial.

Important: make sure the Serial Monitor is closed before uploading to the filesystem. Otherwise, the upload will fail.
When everything is successfully uploaded, open the Serial Monitor at a baud rate of 115200. Press the ESP32 EN/RST button, and it should print the ESP32 IP address.
Open your browser and type the ESP32 IP address. You should get access to the web page that shows the sensor readings. Wait some time until it gathers some data points.

You can select a point to see its value and timestamp.

Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION