ESP8266 NodeMCU: Getting Started with InfluxDB

This guide will get you started quickly with InfluxDB using the ESP8266 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 ESP8266 data to the database. InfluxDB also offers different ways to visualize and organize your data (dashboards, charts, tables, gauges, etc).

ESP8266 NodeMCU Getting Started with InfluxDB Arduino IDE

We have a similar tutorial for the ESP32 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.

InfluxDB Account

2) Select where you want to save your data. I selected the Google Cloud option, but you can select 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 Cloud Getting Started Dashboard

Loading Data in InfluxDB

5) Click on Load Data icon and select Sources.

InfluxDB Cloud Sources

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

InfluxDB Load Data Arduino Client

Click on Initialize Client.

InfluxDB Cloud Arduino 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

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

InfluxDB Cloud Creating ESP8266 bucket

Getting InfluxDB URL and API Token

8) 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.

Arduino Configure InfluxDB Profile

* 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 for you that you could 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 ESP8266 with InfluxDB

We’ll program the ESP8266 using Arduino IDE, so make sure you have the ESP8266 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 ESP8266 with InfluxDB: the InfluxDB Arduino Client Library. This library is also compatible with ESP32 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.
Install InfluxDB Library Arduino IDE

Note: we are using ESP8266 Boards version 3.0.1. Check your boards’ version in Tools > Board > Boards Manager. Then, search for ESP8266 and upgrade to version 3.0.1 (at the moment there are some issues with version 3.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 ESP8266 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

ESP8266 Save Data in InfluxDB

To show you how to save data to InfluxDB using the ESP82662, 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 ESP8266 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 ESP8266WiFiMulti instead of the ESP8266WiFi library to connect the ESP8266 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 ESP8266WiFiMulti library allows the ESP8266 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 ESP8266 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 "REPLACE_WITH_YOUR_BUCKET_NAME"

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 ESP8266 board. If you get any error during compilation, check the following:

  • Check that you have an ESP8266 board selected in Tools > Board.
  • Check your ESP8266 boards installation version in Tools > Board > Boards Manager > ESP8266. Select version 3.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 ESP8266 on-board RESET button to restart the board. It should print something similar on the Serial Monitor:

ESP8266 InfluxDB Write Secure Serial Monitor Demonstration

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

influxDB data explorer

Now, you can visualize your data. Start by selecting the bucket you want. 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 (ESP8266).

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.

InfluxDB ESP8266 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.

Then on Create Dashboard > New 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, ESP8266 Connection Strength. 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.

You can add other visualizations to your dashboard. You just need to add a new cell for each visualization. For example, I have an ESP32 board also saving data to InfluxDB. So, I added a chart for the ESP32 on the same dashboard, as well as a single stat for each board and a chart with both series.

ESP32 and ESP8266 RSSI 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 ESP8266. You learned how to create a database bucket and how to create and send points using the ESP8266. 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 ESP8266 with our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

14 thoughts on “ESP8266 NodeMCU: Getting Started with InfluxDB”

  1. Thanks Sara & Rui,

    as ever a nice clean intro… I send all my and my wife’s house climate (temp, humidity and air quality stuff for different rooms) to influxdb on a Pi4 and use grafana to visualise it. I must admit I need to explore features such as retention schedules etc a bit more …

    thanks again

    Pete

    Reply
  2. The link you gave for people who want to run a local copy of influxdb, may -at least for ubuntu users- result in throwing some errors. For ubuntu users it might be better to install it from the software manager. This site: arubacloud.com/tutorial/how-to-install-influxdb-on-ubuntu-20-04.aspx will give useful info on how to initially get sarted as wel

    Reply
  3. Thank you for posting how to create an InfluxDB data platform. The content is very detailed. For me, it is a new and good project. I will give it a try. Thanks again to Sarah and Rui

    Reply
  4. Hello,

    thank you for this nice how-to.
    But: how dĂłes it work in the other direction?
    eg. I want to get the data from influx-cloud wit an ESP8266?

    Regard
    Georg

    Reply
  5. Very encouraging How-To, many thanks.

    Trying this in March 2023, there is no longer an Arduino option in the Client Libraries. How should I proceed?

    Reply

Leave a Comment

Download Our Free eBooks and Resources

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