ESP32/ESP8266 Send DS18B20 Sensor Readings to InfluxDB

In this ESP32/ESP8266 compatible guide, we will introduce you to InfluxDB and show you how to send DS18B20 sensor readings to the InfluxDB time-series database. We will show you how to create a database bucket and send ESP32/ESP8266 sensor 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 set up an ESP32/ESP8266 InfluxDB database and visualize the temperature readings acquired from DS18B20 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.

ESP32 ESP8266 Send DS18B20 Sensor Readings to InfluxDB

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 ESP32/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 2

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.

InfluxDB create Bucket 3

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_URLINFLUXDB_ORG and INFLUXDB_BUCKET.

InfluxDB create Bucket 4

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 API Token 3

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

ESP32/ESP8266 Record DS18B20 readings to InfluxDB

Now we are all set to send ESP32/ESP8266 data points in InfluxDB. For demonstration purposes, we will interface our ESP32 board with a BME280 sensor and send current temperature readings in both Celsius and Fahrenheit to our ESP32 bucket in InfluxDB. The same procedure is applicable for ESP8266 board as well.

DS18B20 is a temperature sensor which is single wire programmable in nature. It is widely used to measure temperature of chemical solutions and substances which are present in a hard environment. One of the advantages of using this sensor is that we only require a single pin of our ESP boards to transfer data. Thus, it is extremely convenient to use with the micro-controller as we can measure multiple temperatures by using the least number of pins on our development board.

A waterproof version of this sensor is also available in the market. The following figures show the pinout of the DS18B20 sensors.

ds18b20 waterproof pinout diagram
Pin out of waterproof DS18B20

The following diagrams shows the pinout of normal DS18B20 temperature sensor.

ds18b20 pinout diagram

The table below lists the pin configurations:

PinDescription
VCCThis is the pin that powers up the sensor. 3.3V for ESP boards
DataThis pin gives the temperature value
GroundThis pin is connected with the ground

Interfacing DS18B20 sensor with ESP32 and ESP8266

We will now learn how to connect the temperature sensor with ESP32 /ESP8266 board. We will need the following components.

Required Components:

  1. ESP32 /ESP8266
  2. DS18B20  sensor
  3. 4.7k ohm resistor
  4. Breadboard
  5. Connecting Wires

DS18B20 Parasite vs Normal Mode

The DS18B20 sensor can be powered in two different modes.

Normal Mode: The sensor is powered through an external source through the VDD pin and 4.7K ohm pull-up resistor.

Parasite Mode: The sensor obtains the power from its own data line. Hence, no external power supply is required.

ESP32 Schematic Diagram

As you can see in the schematic diagram below, we have used DS10B20 in normal mode and powered the sensor with its Vcc pin from 3.3V pin of ESP32 board. Connect ESP32 device with DS18B20 as shown in the schematic diagram below:

ds18b20 ESP32 schematic diagram

ESP8266 Schematic Diagram

If you are using ESP8266 NodeMCU for this project, connect ESP8266 device with DS18B20 as shown in the schematic diagram below:

ds18b20 interfacing with esp8266 micropython
ESP8266 Connection Diagram

As you can see above, we have powered the sensor using the normal mode. The DS18B20 sensor has three terminals which we saw above in the pinout. The first terminal is grounded with the ESP32 /ESP8266 board. The data line of the sensor, which is the middle terminal, is connected through GPIO14 through a pull-up resistor of 4.7k-ohm. We can choose any other GPIO pin as well. The third terminal is powered by 3.3V from the ESP board.

You can use any other GPIO pin of ESP32 or ESP8266 module. You can refer to these posts to know more about ESP boards GPIO pins:

Setting up Arduino IDE for ESP32/ESP8266 DS18B20 sensor data recording to InfluxDB

We will use Arduino IDE to program our ESP32/ESP8266 boards. Thus, you should have the latest version of Arduino IDE. Additionally, you also need to install the ESP32 and ESP8266 plugins respectively.

If your IDE does not have the plugins installed you can visit the links below: 

Install InfluxDB 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

Installing DS18B20 Arduino Libraries

To use the Dallas DS18B20 sensor we will have to install two libraries.

  1. OneWire library
  2. DallasTemperature library

Follow the steps below to successfully install them. We will use the Library Manager in our Arduino IDE to install the latest versions of the libraries. Open your Arduino IDE and go to Sketch > Include Libraries > Manage Libraries. Type each library name in the search bar and install them both.

ds18b20 one wire library install
ds18b20 dallas temperature library install

After installation of the libraries, restart your IDE.

Sketch: ESP32/ESP8266 Record BME280 Sensor Data to 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 is compatible with both ESP32 and ESP8266 development boards. It creates a data point on the database with tags and fields. After every 10 seconds, it saves the sensor readings taken from DS18B20 connected with your ESP development board.

#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

#if defined(ESP32)
  #include <WiFiMulti.h>
  WiFiMulti wifiMulti;
  #define DEVICE "ESP32"
#elif defined(ESP8266)
  #include <ESP8266WiFiMulti.h>
  ESP8266WiFiMulti wifiMulti;
  #define DEVICE "ESP8266"
#endif

const int SensorDataPin = 14;   
  
OneWire oneWire(SensorDataPin);
DallasTemperature sensors(&oneWire);

float temperature_Celsius;
float temperature_Fahrenheit;


#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 points
Point sensor("measurements");

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

 sensors.begin();
 
  // 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 values into points
  sensor.clearFields();

  sensors.requestTemperatures(); 
  temperature_Celsius = sensors.getTempCByIndex(0);
  temperature_Fahrenheit = sensors.getTempFByIndex(0);
  
  sensor.addField("Temperature Celsius",temperature_Celsius);
  sensor.addField("Temperature Fahrenheit",temperature_Fahrenheit);
  
  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 for temperature: ");
    Serial.println(client.getLastErrorMessage());
  }
  Serial.println("");
  Serial.println("Delay 10s");
  delay(10000);
}

How the Code Works?

The first step is to include all the necessary libraries for this project. WiFiMulti/ESP8266WiFiMulti library will allow us to add multiple Wi-Fi networks inside our sketch and the ESP32/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 ESP32/ESP8266 communication with InfluxDB. Moreover, the other libraries included are for the DS18B20 sensor’s functionality.

Also, create an object of WiFiMulti if using ESP32 and an object of ESP8266WiFiMulti if using ESP8266.

#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>


#if defined(ESP32)
  #include <WiFiMulti.h>
  WiFiMulti wifiMulti;
  #define DEVICE "ESP32"
#elif defined(ESP8266)
  #include <ESP8266WiFiMulti.h>
  ESP8266WiFiMulti wifiMulti;
  #define DEVICE "ESP8266"
#endif

Secondly, we will create a variable to store the GPIO pin through which the sensor’s data pin is connected. We have used GPIO14 in this example.

const int SensorDataPin = 14;

We will require the following instances as well to access the temperature readings. First, we will create a oneWire instance and use the SensorDataPin as an argument inside it. Then we will call the DallasTemperature sensor and pass the oneWire reference which we created above as an argument inside it.

OneWire oneWire(SensorDataPin);
DallasTemperature sensors(&oneWire);

Create two float variables to hold the DS18B20 temperature readings in both Celsius and Fahrenheit.

float temperature_Celsius;
float temperature_Fahrenheit;

InfluxDB Parameters

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 ‘measurements’ 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("measurements");

setup()

Inside the setup() function, we will open the serial communication at a baud rate of 115200. Then we will set the ESP32/ESP8266 in station mode.

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

Then add the Wi-Fi network for the ESP32/ESP8266 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/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 ESP32/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();

Initialize the DS18B20 sensor as well.

sensors.begin();

Now add the tags to the data point. 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 to the data point. 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();

Firstly, we will call the requestTemperatures() method. Then we will use the getTempCByIndex() function and getTempFByIndex() function to retrieve the temperature in degree Celsius and Fahrenheit respectively. Notice that we are passing 0 as a parameter inside the functions. This is because we are using a single DS18B20 sensor. When using multiple sensors this value will increment for each additional sensor.

  sensors.requestTemperatures(); 
  temperature_Celsius = sensors.getTempCByIndex(0);
  temperature_Fahrenheit = sensors.getTempFByIndex(0);

Next, we add the Temperature Celsius and Temperature Fahrenheit fields to our measurements 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("Temperature Celsius",temperature_Celsius);
sensor.addField("Temperature Fahrenheit",temperature_Fahrenheit);

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 10 seconds. This is done by using client.writePoint() and passing the point as the parameter inside it.

  if (!client.writePoint(sensor)) {
    Serial.print("InfluxDB write failed for temperature: ");
    Serial.println(client.getLastErrorMessage());
  }
  Serial.println("");
  Serial.println("Delay 10s");
  delay(10000);

Demonstration

Choose the correct board and COM port before uploading your code to the board. Therefore go to Tools > Board and select ESP32 Dev Module or NodeMCU 1.0.

If you are using ESP32, select the ESP32 Dev module as follows:

select esp32 board

If you are using ESP8266 NodeMCU, select the NodMCU module as follows:

select ESP8266 NodeMCU board

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

Selecting COM PORT ESP32

Click on the upload button to upload the code to ESP32 or ESP8266 development board.

After you have uploaded your code to the ESP32 or ESP8266 development board, press its ENABLE/RST 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 10 seconds.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB 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 bucket that you previously created. In our case it is called ‘ESP32.’ Then to view temperature readings click measurements under the measurement filter, the SSID being used under the SSID filter, Temperature Celsius which is the field tag under the field filter and the device under the device filter. Click Submit to display the data.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data explorer 1

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

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data explorer 2

To view Temperature Fahrenheit readings click measurements under the measurement filter, the SSID being used under the SSID filter, Temperature Fahrenheit which is the field tag under the field filter and the device under the device filter. Click Submit to display the data.

Now you can view the Temperature Fahrenheit data being plotted in a graph.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data explorer 3

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

InfluxDB Data Explorer 4

Build InfluxDB DS18B20 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

Temperature Celsius

Specify the name of the cell. We have given it the name ‘DS18B20 Temperature Reading’. Next choose the visualization from the dropdown menu. We have selected Single Stat.

To obtain the data make a query like we did previously in the data explorer. First click the bucket name, then tick measurements under the measurement filter, the SSID being used under the SSID filter, Temperature Celsius which is the field tag under the field filter and the device name under the device filter. Click the submit button for the changes to take place. You will be able to view the visualization. As we are displaying the temperature reading as a single stat hence we got the reading 28.75. You can also customize the visualization from the CUSTOMIZE button. Here we have customized the visualization by adding °C unit as a suffix. After you are satisfied, then click the tick button for the cell to be added to the dashboard.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data Create Dashboard 1

As you may see, the reading can now be seen in our dashboard.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data Create Dashboard 2

To add more visualizations click ‘ADD CELL’ again and follow the procedure as described previously.

Temperature Fahrenheit

Next to add the visualization for temperature readings in Fahrenheit we will create another cell. Give it a name. Next choose the visualization from the dropdown menu. We have selected Single Stat for this as well.

To obtain the data make a query like we did previously in the data explorer. First click the bucket name, then tick measurements under the measurement filter, the SSID being used under the SSID filter, Temperature Fahrenheit which is the field tag under the field filter and the device under the device filter. Click the submit button for the changes to take place. You will be able to view the visualization. Here we have customized the visualization by adding °F unit as a suffix. Then click the tick button for the cell to be added to the dashboard.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data Create Dashboard 3

This is how our DS18B20 dashboard looks like with the two cells added. You can also change the settings to set the time to refresh your dashboard.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data Create Dashboard 4

We have also added the graphs for both the temperature readings in Celsius and Fahrenheit as well to see the changes in temperature.

ESP32 and ESP8266 send DS18B20 readings to InfluxDB data Create Dashboard 5

You may also like to check:

Leave a Comment