This guide will get you started quickly with InfluxDB using the ESP32 board. InfluxDB is an open-source time series database (TSDB). It’s ideal to store sensor data with timestamps over a determined period. In this tutorial, you’ll set up an InfluxDB bucket to save data from the ESP32.
Updated 14 May 2024
We have a similar tutorial for the ESP8266 NodeMCU board: Getting Started with InfluxDB
Table of Contents
- Introducing InfluxDB
- Creating an InfluxDB Account
- Loading Data in InfluxDB
- Interfacing the ESP32 with InfluxDB
- Visualizing Data on InfluxDB
What is InfluxDB?
InfluxDB is an open-source high-performance time series database (TSDB) that can store large amounts of data per second. Each data point you submit to the database is associated with a particular timestamp. So, it is ideal for IoT datalogging projects like storing data from your weather station sensors.
You can run InfluxDB in InfluxDB Cloud, or locally on your laptop or Raspberry Pi.
“Why use InfluxDB Cloud? It’s a fast, elastic, serverless real-time monitoring platform, dashboarding engine, analytics service and event and metrics processor.”
https://www.influxdata.com/products/influxdb-cloud/
InfluxDB Key Terms
Before getting started, there are some important terms you need to understand. We’ll just take a look at the most relevant terms, you can read the complete glossary. Don’t worry if some of the terms are confusing. You’ll better understand those terms when you start writing to the database.
In InfluDB, a bucket is named location where the time series data is stored. All buckets have a retention period—it defines the duration of time that a bucket retains data. Points with timestamps older than the retention period are dropped.
Data in InfluxDB is stored in tables within rows and columns. A set of data in a row is known as point (similar to a row in a SQL database table). Each point has a measurement, a tag set, a field key, a field value, and a timestamp;
Columns store tag sets (indexed) and fields sets. The only required column is time, which stores timestamps and is included in all InfluxDB tables.
- tag: the key-value pair in InfluxDB’s data structure that records metadata. Tags are an optional part of InfluxDB’s data structure but they are useful for storing commonly-queried metadata; tags are indexed so queries on tags are performant.
- tag key: tag keys are strings and store metadata. Tag keys are indexed so queries on tag keys are processed quickly.
- tag value: tag values are strings and they store metadata. Tag values are indexed so queries on tag values are processed quickly.
- field: the key-value pair in InfluxDB’s data structure that records metadata and the actual data value. Fields are required in InfluxDB’s data structure and they are not indexed – queries on field values scan all points that match the specified time range and, as a result, are not performant relative to tags.
- field key: the key of the key-value pair. Field keys are strings and they store metadata.
- field value: the value of a key-value pair. Field values are the actual data; they can be strings, floats, integers, or booleans. A field value is always associated with a timestamp. Field values are not indexed – queries on field values scan all points that match the specified time range and, as a result, are not performant.
- measurement: the part of InfluxDB’s structure that describes the data stored in the associated fields.
We also recommend taking a quick look at the InfluxDB key concepts.
Creating an InfluxDB Account
If you want to run InfluxDB locally on a Raspberry Pi, follow the next tutorial first: Install InfluxDB 2 on Raspberry Pi. Then, proceed to the Loading Data in InfluxDB section.
1) Go to https://cloud2.influxdata.com/signup and create an InfluxDB account.
2) Select where you want to save your data. Choose the place closer to your location. Insert a name for the Company and Organization.
3) Select the InfluxDB plan. For this example, we’ll be using the Free plan. For most of our IoT projects, the Free plan works just fine.
4) Then, fill out the form to continue.
5) Finally, you’ll be redirected to the resource center.
Loading Data in InfluxDB
6) Click on the Load Data icon and select Sources.
7) Scroll down until you find the Arduino option under the Client Libraries section.
8) Click on Initialize Client.
The page that opens allows you to create buckets, and it also shows some sample code to interface the ESP8266 or ESP32 boards with InfluxDB.
Creating an InfluxDB Bucket
9) Create a new bucket to store your data. Click on + Create Bucket to create a new bucket for this example. You can use the settings by default, or you can customize them.
Getting InfluxDB URL and API Token
10) Get your InfluxDB URL* and other details you’ll need later. Scroll down to the Configure InfluxDB profile snippet. Then, copy the INFLUXDB_URL, INFLUXDB_TOKEN, INFLUXDB_ORG, and INFLUXDB_BUCKET.
* if you’re running InfluxDB locally on a Raspberry Pi, the URL will be the Raspberry Pi IP address on port 8086. For example 192.168.1.106:8086.
API Tokens
If you’ve followed the previous steps, InfluxDB Cloud has already created an API token that you can find in the snippet presented in the previous step. If you go to the Load Data icon and select API Tokens, you’ll find the previously generated API token.
On this page, you can generate a new API token if needed.
At this moment, you should have saved the following:
- InfluxDB Server URL
- InfluxDB Organization
- InfluxDB Bucket Name
- API Token
Interfacing the ESP32 with InfluxDB
We’ll program the ESP32 using Arduino IDe, so make sure you have the ESP32 boards add-on installed:
Alternatively, you can use VS Code with the PlatformIO extension. Check the following tutorial to get started with VS Code + PlatformIO:
Install the InfluxDB Arduino Client Library
There is a library that makes it easy to interface the ESP32 with InfluxDB: the InfluxDB Arduino Client Library. This library is also compatible with ESP8266 boards.
Installation – Arduino IDE
If you’re using Arduino IDE, follow the next steps to install the library.
- Go to Sketch > Include Library > Manage Libraries
- Search for InfluxDB and install the ESP8266 Influxdb library by Tobias Shürg (even though it has ESP8266 in the name, it is also compatible with the ESP32).
Installation – VS Code
If you’re using VS Code with the PlatformIO extension, start by creating an Arduino project for your ESP32 board.
Then, click on the PIO Home icon and then select the Libraries tab. Search for “influxdb“. Select the ESP8266 Influxdb byt Tobias Schürg.
ESP32 Save Data in InfluxDB
To show you how to save data to InfluxDB using the ESP32, we’ll take a look at one of the examples provided by the library. In your Arduino IDE, go to File > Examples > ESP8266 Infuxdb > Secure Write. Or simply copy the code below to your Arduino IDE.
/**
* Secure Write Example code for InfluxDBClient library for Arduino
* Enter WiFi and InfluxDB parameters below
*
* Demonstrates connection to any InfluxDB instance accesible via:
* - unsecured http://...
* - secure https://... (appropriate certificate is required)
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
* Measures signal level of the actually connected WiFi network
* This example demonstrates time handling, secure connection and measurement writing into InfluxDB
* Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status
*
* Complete project details at our blog: https://RandomNerdTutorials.com/
*
**/
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
// WiFi AP SSID
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
// WiFi password
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "REPLACE_WITH_YOUR_DATABASE_URL"
// InfluxDB v2 server or cloud API token (Use: InfluxDB UI -> Data -> API Tokens -> Generate API Token)
#define INFLUXDB_TOKEN "REPLACE_WITH_YOUR_TOKEN"
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG "REPLACE_WITH_YOUR_ORG"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Data -> Buckets)
#define INFLUXDB_BUCKET "ESP32"
// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
// Pacific Time: "PST8PDT"
// Eastern: "EST5EDT"
// Japanesse: "JST-9"
// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "WET0WEST,M3.5.0/1,M10.5.0"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
// Data point
Point sensor("wifi_status");
void setup() {
Serial.begin(115200);
// Setup wifi
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());
// Alternatively, set insecure connection to skip server certificate validation
//client.setInsecure();
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
// Check server connection
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();
// Report RSSI of currently connected network
sensor.addField("rssi", WiFi.RSSI());
// Print what are we exactly writing
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());
}
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
}
Before uploading the code to your board, you need to insert your network credentials, InfludDB URL, organization ID, and bucket name.
This example illustrates how to create a data point on the database with tags and fields. It saves the RSSI of the connected network (Wi-Fi strength between the ESP32 and your router) every 10 seconds.
Let’s take a quick look at how the code works.
How the Code Works
First, it starts by including the required libraries. In this example, it uses the WiFiMulti instead of the WiFi library to connect the ESP32 to a network. It also defines the DEVICE name depending on the selected board.
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
Note: the WiFiMulti library allows the ESP32 to connect to the network with the best RSSI (received signal strength indicator) among a list of added networks. In this example, it only connects to one network.
Include the required InfluxDB libraries to e able to communicate with InfluxDB:
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
Insert your network credentials in the following variables so that the ESP32 can connect to the internet:
// WiFi AP SSID
#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
// WiFi password
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
Insert the InfluxDB server URL on the following lines—the one you’ve gotten in this step:
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "REPLACE_WITH_YOUR_INFLUXDB_URL"
Note: if you’re running InfluxDB locally on a Raspberry Pi, the URL will be the Raspberry Pi IP address on port 8086. For example 192.168.1.106:8086.
Insert your InfluxDB token—saved in this step:
#define INFLUXDB_TOKEN "REPLACE_WITH_YOUR_INFLUXDB_TOKEN"
Add your InfluxDB organization name—check this step.
#define INFLUXDB_ORG "REPLACE_WITH_YOUR_INFLUXXDB_ORGANIZATION_ID"
Finally, add your InfluxDB bucket name:
#define INFLUXDB_BUCKET "ESP32"
Setting your Timezone
You must set your timezone accordingly to these instructions. The easiest way is to check this table and copy your timezone from there. In my case, it’s Lisbon timezone:
#define TZ_INFO "WET0WEST,M3.5.0/1,M10.5.0"
InfluxDB Client
Now that you have all the required settings, you can create an InfluxDBClient instance. We’re creating a secure client that uses a preconfigured certificate—learn more about secure connection here.
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
Point
Then, we create a Point instance called sensor. The point will be called wifi_status on the database. Later in the code, we can refer to that point (sensor) to add tags and fields.
Point sensor("wifi_status");
Note: A set of data in a database row is known as point. Each point has a measurement, a tag set, a field key, a field value, and a timestamp.
setup()
In the setup(), initialize the Serial Monitor.
Serial.begin(115200);
Setup and connect to Wi-Fi:
// Setup wifi
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();
Then, we add tags to our data. Tags are metadata that allows us to better organize our data. It’s also an easier way to query data in a more efficient way later on. In this example, we have the device tag that saves the device name (either ESP32 or ESP8266), and the SSID tag that saves the SSID of the connected network. To add a tag we call the addTag() method to the sensor point. We pass as arguments the tag key and value.
// Add tags
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
Imagine that you have this example running on multiple boards and each board has a unique device tag. Then, it would be easier to query the data relative to a specific device using the device tag. The same for the SSID of the connected network.
The following lines sync the time with the NTP servers.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
The following snippet checks the connection to the InfluxDB server:
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
loop()
In the loop(), we add fields (the actual data) to the point. We start by clearing the point fields:
sensor.clearFields();
We add a field to that point, using the addField() method and passing as arguments, the key (rssi) and the actual RSSI value (WiFi.RSSI()).
sensor.addField("rssi", WiFi.RSSI());
Print in the Serial Monitor what we’re writing to the point:
Serial.println(client.pointToLineProtocol(sensor));
Finally, to actually add the point to the database, we use the writePoint() method on the InfluxDBClient object and pass as argument the point we want to add: client.writePoint(sensor). We run the command inside an if statement for debugging purposes.
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
We write new data to the database every 10 seconds.
//Wait 10s
Serial.println("Wait 10s");
delay(10000);
Demonstration – Visualizing Data on InfluxDB
After inserting all the required settings on the code, you can upload it to your ESP32 board. If you get any error during compilation, check the following:
- Check that you have an ESP32 board selected in Tools > Board.
- Check your ESP32 boards installation version in Tools > Board > Boards Manager > ESP32. Select version 2.0.1 if you’re getting issues with other versions.
After uploading the code to your board, open the Serial Monitor at a baud rate of 115200. Press the ESP32 on-board RST button to restart the board. It should print something similar on the Serial Monitor:
Now, go to your InfludDB account and go to the Data Explorer by clicking on the corresponding icon.
Now, you can visualize your data. Start by selecting the bucket you want—in our case, it’s the ESP32. Then, we need to add filters to select our data. Select the wifi_status under the _measurement field, your SSID under the SSID tag (in this case we just have one SSID, but if we add multiple SSIDs, we could filter the data easily because we added the SSID as a tag). Finally, select the field tag (rrsi) and device (ESP32).
Finally, click on the RUN button.
This will display your data in your chosen format, select the GRAPH option.
Wrapping Up
This was just a quick introduction to InfluxDB with the ESP32. You learned how to create a database bucket and how to create and send points using the ESP32. In this example, we’re sending the RSSI. In an IoT application, you can add sensor readings, current consumption, or any other data that makes sense for your IoT and Home Automation projects.
Follow the next tutorial to learn how to Send BME280 Sensor Readings to InfluxDB with ESP32/ESP8266 boards.
We hope you liked this tutorial and that it helped you get started with InfluxDB. We’ll create more tutorials about this subject soon. So, stay tuned!
- Install InfluxDB 2 on Raspberry Pi
- Monitoring Your Raspberry Pi System using InfluxDB Telegraf
- ESP32/ESP8266: Send BME280 Sensor Readings to InfluxDB
Learn more about the ESP32 with our resources:
- Learn ESP32 with Arduino IDE
- Build Web Servers with ESP32 and ESP8266
- Firebase Web App with ESP32 and ESP8266
- Free ESP32 Projects and Tutorials…
Thanks for reading.
it looks super nice
considering lots of people use Home Assistant with influxdb (and grafana) as addon it would be probably easier with home assitant
Hi, dear RNT-Team and thanks for your outstanding work.
It could be interesting to use hosted InfluxDB, but could be too expensive for private usage.
So a method would be helpful, to acess a privately hosted (i.e. on a Raspberry Pi) InfluxDB-Instance).
Also a means of acessing this data from a Grafana installation, that could also be accessed thru the web.
Thanks
Hi.
Thanks for those suggestions.
We intend to create tutorials about that soon.
Regards,
Sara
Great tutorial as always from RNT! I did it and it works well. I’m also having a RaspberryPI setup with Homebridge and a docker environment with influxdb, grafana etc. and I’m trying to move it to that setup as well.
Hi, thanks as always for the tutorial.
I see here the connection is done directly, but in many tutorials there’s always an MQTT Broker and telegraf.
Is this solution no longer needed?
Hi.
It depends on how your project is build.
You can send data directly from ESP32 to inlfuxDB.
Regards,
Sara
Hi RNT,
cool tutorial !
I’ve created something that could be considered the next step if you like.
My system has the classical architecture controller<>gateways<>nodes.
I wanted to use displays to visualize the data in my camper without having to forward many data to those displays from the controller, so I discovered the Influx subscriptions capability.
A dedicated ESP32 gateway connects to InfluxDB with a UDP connection and just waits until a new packet from InfluxDB arrives, decodes and re-encodes the sensor data in mysensors format and sends it to the displays.
Displays are just mysensors nodes, plain arduinos with a display.
In another case I used an ESP32 with integrated 3.5″ display which connects to influx and gets and shows the data directly.
The nice thing is that the controller is not aware of the traffic between gateway and display nodes, so data are not duplicated in Influx, thing that would have happened using the data forwarding from the controller
Nice development of knowledge about ESP 32 (..86), sensors and data from them. Thanks.
Hi Sara,
quick additional question: In this tutorial you mention we only use WiFiMulti.h. With reference to your WiFiMulti tutorial you mentioned that we need both, WiFi.h and WiFiMulti.h. What is the difference?
Many thanks.
Hello!
This tutorials works perfect over WIFI but how can we get timestamp with an ESP32 SIM800?
Because it can’t connect with NTP server.
Thanks for your amazing work!
The hosting locations changed and there is no Google Cloud anymore, at least when I choose Frankfurt as a european location. AWS seems to be the only host and I haven’t found Arduino Client Library as a source.
I have the same issue with step 6 — I cannot find the Arduino option under the Client Libraries section. Otherwise, looks like a well written tutorial.
Hi,
I use this on an ESP32:
When it executes this line:
sensor.addField(“rssi”, WiFi.RSSI());
it makes a error
Writing: wifi_status,device=ESP32,SSID=WLAN-** rssi=-54i
I do not know where it gets this funny “i” on the end.
Do you hve any idea?
what if i wanna use another tag?
thanks anyway it’s a very great tutorial
Hey there,
thanks for another awesome tutorial! Everything on ESP32 side is working brilliant, publishing data and receiving them in InfluxDB cloud works like a charm.
Unfortunately my InfluxDB cloud webpage looks differently and the sidemap only shows three points: Load Data, Data Explorer and Settings.
The Dashboard point is not visible and I’m wondering how to create one? Maybe I missed something?
Best regards and thanks again!
Moritz
Hi.
Do you mean that you don’t have the “Dashboard” icon on your InfluxDB page?
Can you show me a printscreen of your dashboard? (to share a picture, upload it to google drive and then share a link to the file).
Regards,
Sara
I have exactly the same problem: no dashboard icon available.
I thought this could be a change in free plan but I couldn’t find any confirm about this.
To reproduce: create a new account and have a look.
It is also impossible to choose where to store data, only AWS is available
Is it a way to control ESP32 from influxdb/grafana? I think about LED on/off, send data (integer, float, text)… like in your Firebase or Ubidots tutorials.
BTW I also can not find dashboard icon in my influxdb page created today.
Hi.
That is not possible with InfluxdB.
Regards,
Sara
Please also make an article teaching the way to connect ESP32 with InfluxDB but with Micropython
Always love your tutorials!
Is there anyway to use micropython to send data to influxdb 1.8.x from an esp32?
I’ve tried
res = urequests.post(url, headers=headers, data=data)
and everything looks good via print(url) etc but nothing gets logged into influxdb.
I prefer to use python/ micropython over C and sketches but I am wracking my brains over this. I am successful when I use a simple curl command in my terminal though.
curl -i -XPOST ‘http://x.x.x.x:8086/write?db=sensor_data&u=xxx&p=xxx’ –data-binary ‘esp32,location=couch humidity=1,pressure=3,temperature=3’
but I cannot translate that to micropython. Any thoughts would be GREATLY appreciated.
Your tutorials and the information that you unselfishly provide is almost unparalleled, and it’s saved me many hours of work. A small issue that would also add some value is to put a time stamp on such comments as “… at the moment there are some issues with version 2.0.2, so don’t select that one …”. Thanks.
This tutorial on using ESP32 with InfluxDB is exactly what I needed! The step-by-step instructions and clear explanations make it easy to follow. I’m excited to set up my own IoT projects with this combination. Thanks for the detailed guide!