Visualize and Graph ESP-32 Sensor Data
Visualize and Graph ESP-32 Sensor Data
If you’re using a hosting provider with cPanel, you can search for “File
Manager”:
Edit the newly created file (post-data.php) and copy the following snippet:
<?php
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com
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.
*/
$servername = "localhost";
// Keep this API Key value to be compatible with the ESP32 code provided
in the project page. If you change this value, the ESP32 sketch needs to
match
$api_key_value = "tPmAT5Ab3j7F9";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$api_key = test_input($_POST["api_key"]);
if($api_key == $api_key_value) {
$value1 = test_input($_POST["value1"]);
$value2 = test_input($_POST["value2"]);
$value3 = test_input($_POST["value3"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
http://example.com/post-data.php
4. PHP Script – Visualize Database
Content in a Chart
Create another PHP file in the /public_html directory that will plot the
database content in a chart on a web page. Name your new file: esp-
chart.php
Edit the newly created file (esp-chart.php) and copy the following code:
<!--
Rui Santos
Complete project details at https://RandomNerdTutorials.com
The above copyright notice and this permission notice shall be included
in all
copies or substantial portions of the Software.
-->
<?php
$servername = "localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, value1, value2, value3, reading_time FROM Sensor order
by reading_time desc limit 40";
$result = $conn->query($sql);
$value1 = json_encode(array_reverse(array_column($sensor_data,
'value1')), JSON_NUMERIC_CHECK);
$value2 = json_encode(array_reverse(array_column($sensor_data,
'value2')), JSON_NUMERIC_CHECK);
$value3 = json_encode(array_reverse(array_column($sensor_data,
'value3')), JSON_NUMERIC_CHECK);
$reading_time = json_encode(array_reverse($readings_time),
JSON_NUMERIC_CHECK);
/*echo $value1;
echo $value2;
echo $value3;
echo $reading_time;*/
$result->free();
$conn->close();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body {
min-width: 310px;
max-width: 1280px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>ESP Weather Station</h2>
<div id="chart-temperature" class="container"></div>
<div id="chart-humidity" class="container"></div>
<div id="chart-pressure" class="container"></div>
<script>
</script>
</body>
</html>
http://example.com/esp-chart.php
That’s it! If you see three empty charts in your browser, it means that
everything is ready. In the next section, you’ll learn how to publish your
ESP32 or ESP8266 sensor readings.
To build the charts, we’ll use the Highcharts library. We’ll create three
charts: temperature, humidity and pressure over time. The charts display
a maximum of 40 data points, and a new reading is added every 30
seconds, but you change these values in your code.
5. Preparing Your ESP32 or
ESP8266
This project is compatible with both the ESP32 and ESP8266 boards. You
just need to assemble a simple circuit and upload the sketch provided to
insert temperature, humidity, pressure and more into your database
every 30 seconds.
Parts Required
For this example we’ll get sensor readings from the BME280 sensor.
Here’s a list of parts you need to build the circuit for this project:
Schematics
The BME280 sensor module we’re using communicates via I2C
communication protocol, so you need to connect it to the ESP32 or
ESP8266 I2C pins.
ESP32/ESP8266 Code
We’ll program the ESP32/ESP8266 using Arduino IDE, so you must have
the ESP32/ESP8266 add-on installed in your Arduino IDE. Follow one of
the next tutorials depending on the board you’re using:
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com
The above copyright notice and this permission notice shall be included
in all
copies or substantial portions of the Software.
*/
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "http://example.com/post-data.php";
// Keep this API Key value to be compatible with the PHP code provided in
the project page.
// If you change the apiKeyValue value, the PHP file /post-data.php also
needs to have the same key
String apiKeyValue = "tPmAT5Ab3j7F9";
/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software
SPI
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
void loop() {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
//Send an HTTP POST request every 30 seconds
delay(30000);
}
You need to modify the following lines with your network credentials: SSID
and password. The code is well commented on where you should make
the changes.
This project is already quite long, so we won’t cover in detail how the code
works, but here’s a quick summary:
Import all the libraries to make it work (it will import either the
ESP32 or ESP8266 libraries based on the selected board in
your Arduino IDE)
Set variables that you might want to change (apiKeyValue)
The apiKeyValue is just a random string that you can modify. It’s
used for security reasons, so only anyone that knows your API
key can publish data to your database
Initialize the serial communication for debugging purposes
Establish a Wi-Fi connection with your router
Initialize the BME280 to get readings
Then, in the loop() is where you actually make the HTTP POST request
every 30 seconds with the latest BME280 readings:
// Your Domain name with URL path or IP address with path
http.begin(serverName);
Demonstration
After completing all the steps, let your ESP board collect some readings
and publish them to your server.
If everything is correct, this is what you should see in your Arduino IDE
Serial Monitor:
If you open your domain name in this URL path:
http://example.com/esp-chart.php
You should see the all the readings stored in your database. Refresh the
web page to see the latest readings:
You can also go to phpMyAdmin to manage the data stored in
your Sensor table. You can delete it, edit, etc…
Wrapping Up
In this tutorial you’ve learned how to publish sensor data into a database
in your own server domain that you can access from anywhere in the
world. This requires that you have your own server and domain
name (you can also use a Raspberry Pi for local access).
With this setup you control your server and can move to a different host if
necessary. There are many cloud solutions both free and paid that you
can use to publish your readings, but those services can have several
disadvantages: restrictions on how many readings you can publish,
number of connected devices, who can see your data, etc. Additionally,
the cloud service can be discounted or change at any time.
The example provided is as simple as possible so that you can understand
how everything works. After understanding this example, you may change
the web page appearance, publish different sensor readings, publish from
multiple ESP boards, and much more.
If you like ESP32, you might consider enrolling in our course “Learn ESP32
with Arduino IDE“. You can also access our free ESP32 resources here.
Thank you for reading.