ESP32: Getting Started with InfluxDB

This guide will get you started quickly with InfluxDB using the ESP32 board. InfluxDB is an open-source time series database (TSDB). So, it is ideal to store sensor data with timestamps over a determined period of time. In this tutorial, you’ll set up an InfluxDB bucket to save data, and you’ll learn how to save ESP32 data to the database. InfluxDB also offers different ways to visualize and organize your data (dashboards, charts, tables, gauges, etc).

ESP32 Board Getting Started with InfluxDB Arduino IDE

We have a similar tutorial for the ESP8266 NodeMCU board: Getting Started with InfluxDB

Table of Contents

What is 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.

Creating an InfluxDB Account

2) Select where you want to save your data. I choose the Google Cloud option, but you can choose one of the other options. Select the region, it should be the closest to your location. Then, enter something on the Company Name field, and agree to the terms before proceeding.

InfluxDB select provider

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.

InfluxDB select plan

4) After selecting the plan, you’ll be redirected to the Getting Started page.

InfluxDB Getting Started Page

Loading Data in InfluxDB

5) Click on LOAD YOUR DATA.

6) Scroll down until you find the Arduino option under the Client Libraries section.

InfluxDB Load Data Arduino 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.

InfluxDB Load Data Arduino

Creating an InfluxDB Bucket

7) You can use the default bucket, or create a new bucket. We’ll create a new one. Click on + Create Bucket to create a new bucket for this example. You can change the settings by default, or you can customize them.

InfluxDB create bucket

Getting InfluxDB URL

8) Get your InfluxDB URL* and other details you’ll need later. Scroll down to the Initialize the Client snippet. Then, copy the INFLUXDB_URL, INFLUX_DB_ORG, and INFLUX_DB_BUCKET.

InfluxDB Initialize Arduino Client

* 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.

Generate an API Token

Now, you need to generate an API token so that your devices can write and/or read to your bucket.

9) Select the up-arrow icon and click on API Tokens.

InfluxDB API Tokens Menu

10) Click on + Generate API Token > All Access API Token.

InfluxDB Generate All Access API Token

11) Give a description that identifies that API token. Since it will be used by the ESP32, I simply wrote “ESP32”.

Generate All Access API Token Description

12) A new window with your API token will show up. Copy the API Token to a safe place because you’ll need it later. You won’t be able to see the API token again!

InfluxDB API Token Generator

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.

  1. Go to Sketch Include Library > Manage Libraries
  2. 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).
Install InfluxDB Library Arduino IDE

Note: we are using ESP32 Boards version 2.0.1. Check your boards version in Tools > Board > Boards Manager. Then, search for ESP32 and upgrade to version 2.0.1 (at the moment there are some issues with version 2.0.2, so don’t select that one).

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.

Install InfluxDB library VS Code

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);
}

View raw code

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:

ESP32 WriteSecure InfluxDB Example Serial Monitor

Now, go to your InfludDB account and go to the Data Explorer by clicking on the corresponding icon.

InfluxDB data explorer menu

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 SUBMIT button.

This will display your data in your chosen format. In the upper left corner, you can select different ways to visualize the data.

ESP32 InfluxDB Data Explorer

You can create a dashboard to show multiple data visualizations in different formats (gauges, histogram, single stat, etc.) or different data on the same page.

Creating a Dashboard

Click on the dashboard icon and then on Create Dashboard > New dashboard.

InfluxDB - Create Dashboard

Add a cell. Make the query to get your data and select the visualization you want. Give a name to the cell, for example, ESP32 RSSI History. You can also click on the Customize button to customize the graph. Finally, click on the icon in the top right corner to add the visualization as a cell to your dashboard.

ESP32 InfluxDB RSSI History Add Cell

You can add other visualizations to your dashboard. You just need to add a new cell for each visualization. For example, I added a table and a single stat that shows the current SSID.

ESP32 WiFi Connection Strength InfluxDB Dashboard

You can move your cells to different positions and organize the dashboard in a way that makes sense for you. You can also customize the way the data is refreshed and how many data points you want to see (up to the past 30 days on the free cloud plan).

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!

Learn more about the ESP32 with our resources:

Thanks for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

9 thoughts on “ESP32: Getting Started with InfluxDB”

  1. 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

    Reply
  2. 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

    Reply
  3. 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.

    Reply
  4. 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?

    Reply
    • Hi.
      It depends on how your project is build.
      You can send data directly from ESP32 to inlfuxDB.
      Regards,
      Sara

      Reply
  5. 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

    Reply
  6. 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.

    Reply

Leave a Reply to Sara Santos Cancel reply

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.