In this ESP32 guide, we will introduce you to InfluxDB and how to use it with ESP32 development board. We will show you how to create a database bucket and send ESP32 data to the InfluxDB time series database. Moreover, we will also show you how to build your dashboard so that you are able to view your data in a more meaningful manner e.g. charts, graphs, etc. By the end of this tutorial, you will be able to know how to set up an ESP32 InfluxDB database and visualize the data in a dashboard. One of the great features of using the InfluxDB database is that you can store your data in timestamps over a determined period of time. This makes it extremely handy to use in IoT projects where data logging with time is of importance.
We have a similar guide with ESP8266:
InfluxDB Introduction
InfluxDB is an open-source time series database. It is used for storing and acquiring time series data commonly used in IoT applications, real-time data analysis, operations monitoring, etc. A vast amount of data can be efficiently stored every second with timestamps associated with each data point.
Let us define some InfluxDB key terms that are commonly used while using this database.
Bucket: A bucket is a specified place where the data is stored. While creating a bucket you specify the name and the time period for the data to get deleted.
Point: A point consists of a set of data in a row. It comprises of a measurement, tag set, field key, field value and a timestamp.
Tag (tag key and tag value): The columns in a data are known as tags. A tag consists of a set of data that gives us information about other data that are usually queried. Although they are optional but it helps in organizing the data in an efficient manner. They are indexed.
Field (field key and field value): A field consists of a field key and a field value stored in their respective columns. They are not indexed. Here a field key is a string type that depicts the name of the field. A field value on the other hand depicts the value of the field. It can be type string, float, int or boolean.
Measurement: This shows the data (tags, fields, timestamps) stored in the related fields. A measurement name is a string and is chosen in such a way that it describes the data it holds.
Recommended Reading: InfluxDB data elements
Setting up an InfluxDB Database
Now let us see how to easily set up our InfluxDB database for ESP32 data logging. Firstly, head over to the official InfluxDB website (https://www.influxdata.com/) and click the ‘Get InfluxDB’ button as highlighted below.
You will have to create a free InfluxDB cloud account. You can either continue with your Google or Microsoft account or login by providing your details as shown below to create an account.
The next step is to choose where you would like to store the data. We are selecting Google Cloud as storage. You also have the option of using Amazon web services and Microsoft Azure. Moreover, the company name will also be required. Do not forget to tick the agreement after reading it.
Next up we will be asked to select a plan. We will stick with the ‘Free’ plan as it works well with our projects.
Now the get started page will open up. By now we have successfully logged into InfluxDB, set our storage destination and chosen our InfluxDB cloud plan. Now we are ready to load data.
Load Data
To load data to InfluxDB start by clicking the More button as highlighted below.
This will open the load data section. Here under the ‘Sources’ tab select Arduino as the client library.
This will open up the bucket page with sample code as well. Currently we don’t have any bucket. First, we will have to create a bucket. Click ‘+ CREATE BUCKET’ to proceed forward.
Give a name to your bucket and customize the option to delete data according to your requirements. After that click ‘CREATE’ to complete the process of bucket creation.
Now as you may see, in the bucket page we can view the bucket we just created. We had named it ‘ESP32’ and it can be found under the bucket section. Double click on it for the bucket to get selected.
Obtain InfluxDB Parameters (URL, ORG and Bucket)
This is a very important step. We will obtain the InfluxDB URL, ORG and Bucket. These parameters will be used inside our program sketch to successfully send data to InfluxDB.
Inside our ESP32 bucket, head over to ‘Initialize the Client’ section. Here you can view the definitions of different InfluxDB parameters. Copy the INFLUXDB_URL, INFLUXDB_ORG and INFLUXDB_BUCKET.
Obtain API Token
The next important step is to generate an API Token. This is also required for securely reading/writing to the InfluxDB database.
At the far left side, click the arrow icon as shown below and then select API Tokens.
Now click + GENERATE API TOKEN and then click All Access API Token as highlighted below:
Give a description to your All Access API Token and save it.
Now your API token will get generated. Copy it and save it securely. You will not be able to view it again.
Install InfluxDB Library in Arduino IDE
We will use Arduino IDE to program our ESP32. Thus, you should have the latest version of Arduino IDE. Additionally, you also need to install the ESP32 plugin.
If your IDE does not have the plugin installed you can visit the link below: Installing ESP32 library in Arduino IDE and upload code.
Open Arduino IDE and click on Sketch > Library > Manage Libraries
The following window will open up.
Type ‘Influxdb’ in the search bar and press enter. Install the latest version of the library as shown below. This library is compatible with both ESP8266 and ESP32 development boards.
After installation of the library, restart your IDE.
Send ESP32 ADC Voltage Measurement in InfluxDB
Now we are all set to send ESP32 data points in InfluxDB. For demonstration purposes, we will interface our ESP32 board with a potentiometer and send voltage readings to our ESP32 bucket in InfluxDB.
We will connect the potentiometer with an analog channel on our ESP32 board and then measure its voltage. By turning the upper knob of the potentiometer, variable input voltages would be supplied which would be converted to their corresponding digital values through the ADC module in our ESP32 board. The following components are required to perform this procedure:
Required Components
- ESP32 DEVKIT board
- Breadboard
- Potentiometer
- Connecting Wires
ESP32 Connection Diagram with Potentiometer
The below picture shows the schematic for the ESP32 module with a potentiometer. Assemble your circuit as follows:
As we can see the one terminal of the potentiometer is powered by 3.3V (green), the center terminal is connected to GPIO pin (blue) and the last one is grounded (black). For ESP32 the blue wire connects the GPIO32 which is ADC1_CH4 or ADC1 channel 4.
Make sure you choose an appropriate ESP32 analog pin that is not shared by other peripherals especially Wi-Fi.
Sketch: ESP32 Save Data in InfluxDB
Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. Remember to change the Wi-Fi credentials, InfluxDB URL, ORG, Bucket name and the API token. Additionally, set the time zone string according to your location to synch time correctly.
This sketch creates a data point on the database with tags and fields. After every 5 seconds, it saves the voltage reading taken from ESP32 ADC channel converted into a digital value.
#include <WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#define WIFI_SSID "WRITE_YOUR_SSID"
#define WIFI_PASSWORD "WRITE_YOUR_PASSWORD"
#define INFLUXDB_URL "WRITE_YOUR_URL"
#define INFLUXDB_TOKEN "WRITE_YOUR_API_TOKEN"
#define INFLUXDB_ORG "WRITE_YOUR_ORG"
#define INFLUXDB_BUCKET "WRITE_YOUR_BUCKET"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
#define TZ_INFO "PKT-5"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// Data point
Point sensor("voltage_status");
const int Analog_channel_pin= 32;
int ADC_VALUE = 0;
float voltage_value;
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
// Add tags
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void loop() {
// Store measured value into point
sensor.clearFields();
ADC_VALUE = analogRead(Analog_channel_pin);
delay(1000);
voltage_value = (ADC_VALUE * 3.3 ) / (4095);
delay(1000);
sensor.addField("Voltage",voltage_value);
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensor));
// If no Wifi signal, try to reconnect it
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.println("Delay 5s");
delay(5000);
}
How the Code Works?
The first step is to include the WiFiMulti library in the sketch. This will allow us to add multiple Wi-Fi networks inside our sketch and the ESP32 connects with the strongest network. However, we will use a single network in this example. Secondly, also include the InfluxDB libraries that we just installed. This will ensure an easy and successful ESP32 communication with InfluxDB.
#include <WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
Next, create an object of WiFiMulti as shown below:
WiFiMulti wifiMulti;
Specify the name of the device that you will be using. In our case it is ESP32.
#define DEVICE "ESP32"
The next step is very important. Carefully define your Wi-Fi SSID, Wi-Fi password, InfluxDB URL, InfluxDB ORG, InfluxDB API token and InfluxDB bucket name. The parameters related to InfluxDB are the ones that we previously acquired and saved.
#define WIFI_SSID "WRITE_YOUR_SSID"
#define WIFI_PASSWORD "WRITE_YOUR_PASSWORD"
#define INFLUXDB_URL "WRITE_YOUR_URL"
#define INFLUXDB_TOKEN "WRITE_YOUR_API_TOKEN"
#define INFLUXDB_ORG "WRITE_YOUR_ORG"
#define INFLUXDB_BUCKET "WRITE_YOUR_BUCKET"
Now, define the time zone according to your location. This is necessary to synch the time.
Refer to the link given below to obtain the time zone closest to your location and define it in code.
https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
We have set the time zone for Asia/Karachi hence we use PKT-5.
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
#define TZ_INFO "PKT-5"
The next step is to create an InfluxDBClient instance. This will generate a secure client with a preconfigured certificate.
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
Here we will create a data point called ‘voltage_status’ in the InfluxDB database. This will consist of a measurement, tag set, field key, field value and timestamp. In this case the point instance is called sensor.
Point sensor("voltage_status");
Moreover, specify the analog pin of ESP32 connected with the potentiometer as Analog_channel_pin. Then create two variables. The int variable is used to store the ADC value and the float variable is used to store the voltage value.
const int Analog_channel_pin= 32;
int ADC_VALUE = 0;
float voltage_value;
setup()
Inside the setup() function, we will open the serial communication at a baud rate of 115200. Then we will set the ESP32 in station mode.
Serial.begin(115200);
WiFi.mode(WIFI_STA);
Then add the Wi-Fi network for the ESP32 to connect with. This will be done using the addAP() method on the WiFiMulti object. Here we will specify two parameters. The first parameter is the SSID and the second parameter is the password. You can add as many networks as you want. We are only adding a single network.
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
We will use the run() method on the WiFimulti object, to connect ESP32 with the strongest Wi-Fi connection. This returns the status of the Wi-Fi connection.
The following lines of code will be used to monitor if the ESP32 is connected or not. While the connection is lost, it will try to connect again.
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Now add the tags to the data. This is done using the addTag() method on the point instance. It takes in two parameters. The first is the tag key and the second is the tag value.
Here we are adding two tags. One for the device name and another for the Wi-Fi SSID.
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
Next we will synch the time with the NTP server using the timeSync() function.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
Lastly, the InfluxDB client confirms its connection to the server. A relevant message will be printed in the serial monitor in either case if the client is connected or not.
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
loop()
Inside the loop() function, we store the data to the point. First of all we will clear all the fields of the point instance.
sensor.clearFields();
Then we read the analog input and save it in the variable ‘ADC_VALUE’. After a delay of 1 second, we will convert the digital value of ADC_VALUE into voltage. ADC_VALUE is multiplied with a resolution of ESP32 ADC which is 3.3 / 4095. Resolution is also know as a minimum step of ADC for each corresponding value of voltage. For example, if ADC_VALUE counts 10, its mean it has taken 10 steps or value at the input pin is 10 times the resolution of ADC.
ADC_VALUE = analogRead(Analog_channel_pin);
delay(1000);
voltage_value = (ADC_VALUE * 3.3 ) / (4095);
delay(1000);
Next, we add the Voltage field to our point. This is done by using the addField() method on the Point instance. We specify the key as the first parameter and the value as the second parameter.
sensor.addField("Voltage",voltage_value);
Then we will display on the serial monitor the information that is being written to the point. The data will be shown in the Line Protocol form.
Serial.print("Writing: ");
Serial.println(client.pointToLineProtocol(sensor));
Additionally, connect to the Wi-Fi network incase of disconnection.
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
Lastly, write the point to the database after every 5 seconds. This is done by using client.writePoint() and passing the point as the parameter inside it.
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.println("Delay 5s");
delay(5000);
Demonstration
Choose the correct board and COM port before uploading your code to the board.
Go to Tools > Board and select ESP32 Dev Module.
Next, go to Tools > Port and select the appropriate port through which your board is connected.
Click on the upload button to upload the code into the ESP32 development board. After you have uploaded your code to the ESP32 development board press its ENABLE button.
In your Arduino IDE, open up the serial monitor and set the baud rate to 115200. First the board will connect with the local Wi-Fi then the time will sync. Next the client gets connected to InfluxDB server and you can view the data being written to the database after every 5 seconds. Move the knob of the potentiometer to vary the voltage readings.
Visualize Data in InfluxDB
Now let us visualize the data that we sent to InfluxDB Cloud. Login to your InfluxDB account and head over to Data Explorer as shown below.
This will open the Data Explorer page. Here we will be able to graph the data that is being sent to the InfluxDB cloud. First click the ESP32 bucket, then tick voltage_status under the measurement filter, the SSID being used under the SSID filter, voltage which is the field tag under the field filter and ESP32 under the device filter. Click Submit to display the data.
Now you can view the data being plotted in a graph. You can also customize it as well.
Moreover, you can also display the data in various formats including band, gauge, histogram, map etc. from the dropdown below.
Build InfluxDB Dashboard
Now let us show you how to display the data in various formats on the same page. We will create a dashboard. Head over to the Dashboard icon and click it.
This will open the Dashboard open. Currently, we do not have any dashboard created. Click ‘+ CREATE DASHBOARD’ button as highlighted below:
Give a name to your dashboard. Then click ADD CELL to add a visualization.
Specify the name of the cell. We have given it the name ‘ESP32 Voltage Readings. Next choose the visualization from the dropdown menu. We have selected Graph. To obtain the data make a query like we did previously in the data explorer. First click the ESP32 bucket, then tick voltage_status under the measurement filter, the SSID being used under the SSID filter, voltage which is the field tag under the field filter and ESP32 under the device filter. Click the submit button. Then click the tick button for the changes to take place.
As you may see, the graph can now be seen in our dashboard. To add more visualizations click ‘ADD CELL’ again and follow the procedure as described previously.
We have added a graph and a gauge to our dashboard to view the voltage readings. Additionally, we have customized the gauge by setting its maximum and minimum values within the voltage limits. You can also change the settings to refresh your dashboard.
You may also like to read: