ESP8266 Getting Started with InfluxDB Time Series Database

In this ESP8266 guide, we will introduce you to InfluxDB and how to use it with ES8266 NodeMCU. We will show you how to create a database bucket and send ESP8266 data to the InfluxDB 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 setup an ESP8266 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 set period of time. This makes it extremely handy to use in IoT projects where data logging with time is of importance.

ESP8266 Getting Started with InfluxDB Time Series Database

We have a similar guide with ESP32:

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.

InfluxDB logo

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 ESP8266 data logging. Firstly, head over to the official InfluxDB website (https://www.influxdata.com/) and click the ‘Get InfluxDB’ button as highlighted below.

InfluxDB create account 1

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.

InfluxDB create account 2

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.

InfluxDB store data

Next up we will be asked to select a plan. We will stick with the ‘Free’ plan as it works well with our projects.

InfluxDB choose plan

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.

InfluxDB getting started page

Load Data

To load data to InfluxDB start by clicking the More button as highlighted below.

InfluxDB load data

This will open the load data section. Here under the ‘Sources’ tab select Arduino as the client library.

InfluxDB load data 2

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.

InfluxDB create Bucket 1

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.

InfluxDB create bucket for esp8266 1

Now as you may see, in the bucket page we can view the bucket we just created. We had named it ‘ESP8266’ and it can be found under the bucket section. Double click on it for the bucket to get selected.

InfluxDB create bucket for esp8266 2

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

InfluxDB create bucket for esp8266 3

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.

InfluxDB API Token 1

Now click + GENERATE API TOKEN and then click All Access API Token as highlighted below:

InfluxDB API Token 2

Give a description to your All Access API Token and save it.

InfluxDB create API Token

Now your API token will get generated. Copy it and save it securely. You will not be able to view it again.

InfluxDB API Token 4

Install InfluxDB Library in Arduino IDE

We will use Arduino IDE to program our ESP8266 development board. Thus, you should have the latest version of Arduino IDE. Additionally, you also need to install the ESP8266 plugin.

If your IDE does not have the plugin installed you can visit the link below: Installing ESP8266 library in Arduino IDE

Open Arduino IDE and click on Sketch > Library > Manage Libraries

MPU-6050 Install library

The following window will open up.

search library Arduino IDE

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.

Install InfluxDB Library

After installation of the library, restart your IDE.

Send ESP8266 ADC Voltage Measurement in InfluxDB

Now we are all set to send ESP8266 data points in InfluxDB. For demonstration purposes, we will interface our ESP8266 board with a potentiometer and send voltage readings to our ESP8266 bucket in InfluxDB.

We will connect the potentiometer with the analog channel on our ESP8266 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 ESP8266 board. The following components are required to perform this procedure:

Required Components

  1. ESP8266 NodeMCU
  2. Breadboard
  3. Potentiometer
  4. Connecting Wires

ESP8266 Connection Diagram with Potentiometer

The below picture shows the schematic for the ESP8266 module with a potentiometer. Assemble your circuit as follows:

ESP8266 NodeMCU ADC with Potentiometer
Schematic of ESP8266 to read Analog input

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 ESP8266 the blue wire is connected with GPIO0 which is ADC0.

Sketch: ESP8266 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 sync 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 ESP8266 ADC channel converted into a digital value. 

#include <ESP8266WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"

#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 ADC_pin = A0;  
int ADC_reading = 0;  
float voltage_value;

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

  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() {
 
  sensor.clearFields();
  
  ADC_reading = analogRead(ADC_pin);
  voltage_value = ADC_reading * 3.3 / 1023;

  sensor.addField("Voltage",voltage_value);
  // 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());
  }

  Serial.println("Delay 5s");
  delay(5000);
}

How the Code Works?

The first step is to include the ESP8266WiFiMulti library in the sketch. This will allow us to add multiple Wi-Fi networks inside our sketch and the ESP8266 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 ESP8266 communication with InfluxDB.

#include <ESP8266WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

Next, create an object of ESP8266WiFiMulti as shown below:

ESP8266WiFiMulti wifiMulti;

Specify the name of the device that you will be using. In our case it is ESP8266.

#define DEVICE "ESP8266"

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 sync 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 ESP8266 connected with the potentiometer as ADC_pin. Then create two variables. The int variable is used to store the ADC reading and the float variable is used to store the voltage value.

const int ADC_pin = A0;  
int ADC_reading = 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 ESP8266 in station mode.

Serial.begin(115200);
WiFi.mode(WIFI_STA);

Then add the Wi-Fi network for the ESP8266 to connect with. This will be done using the addAP() method on the ESP8266WiFiMulti 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 ESP8266WiFimulti object, to connect ESP8266 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 ESP8266 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 sync 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 will first find out the ADC value according to the varying voltage using analogRead(). We will pass the ADC pin connected to the potentiometer as an argument inside it. This will be stored in the integer variable we defined previously ‘ADC_reading.’ Next we will calculate the analog voltage by multiplying the ADC digital value with the resolution of ESP8266 ADC which is 3.3/1023. It will provide output in the form of voltage.

  ADC_reading = analogRead(ADC_pin);
  voltage_value = ADC_reading * 3.3 / 1023;

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 ESP8266 NodeMCU board. Go to Tools > Board and select ESP8266 NodeMCU Module.

select ESP8266 NodeMCU board

Next, go to Tools > Port and select the appropriate port through which your board is connected.

ESP8266 COM Port

Now click on the upload button to upload code to ESP8266 NodeMCU. After that open the Arduino serial monitor and press the enable button on ESP8266 NodeMCU:

ESP8266 NodeMCU reset 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.

ESP8266 Send Data in InfluxDB Voltage Readings demo serial monitor

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.

InfluxDB Data Explorer

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 ESP8266 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 ESP8266 under the device filter. Click Submit to display the data.

InfluxDB Data Explorer for esp8266 1

Now you can view the data being plotted in a graph. You can also customize it as well.

InfluxDB Data Explorer for esp8266 2

Moreover, you can also display the data in various formats including band, gauge, histogram, map etc. from the dropdown below.

InfluxDB Data Explorer 4

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

InfluxDB Create Dashboard

This will open the Dashboard open. Currently, we do not have any dashboard created. Click ‘+ CREATE DASHBOARD’ button as highlighted below:

InfluxDB Create Dashboard 1

Give a name to your dashboard. Then click ADD CELL to add a visualization.

InfluxDB Create Dashboard 2

Specify the name of the cell. We have given it the name ‘ESP8266 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 ESP8266 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 ESP8266 under the device filter. Click the submit button. Then click the tick button for the changes to take place.

InfluxDB create dashboard for esp8266 1

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.

InfluxDB create dashboard for esp8266 2

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.

InfluxDB create dashboard for esp8266 3

Leave a Comment