ESP32/ESP8266: Send BME280 Sensor Readings to InfluxDB

For a more extensive introduction to InfluxDB, inspect the following tutorials prior to proceeding:

If you do not have an InfluxDB account, comply with the next steps.

ESP32 ESP8266 Sensor Readings Dashboard InfluxDB

For this job, you require the complying with parts *:

What is InfluxDB?

influxdb what it is

* you can likewise evaluate the task with arbitrary values rather of sensing unit analyses, or you can utilize any kind of other sensing unit you’re familiar with.

Insert the InfluxDB web server URL on the adhering to lines–:

Note: if you’re running InfluxDB locally on a Raspberry Pi, the URL will certainly be the Raspberry Pi IP address on port 8086.

https://www.influxdata.com/products/influxdb-cloud/

For an extra thorough introduction to InfluxDB, check the complying with tutorials before case:

  • ESP32: Getting Started with InfluxDB
  • ESP8266: Getting Started with InfluxDB

Creating an InfluxDB Account

If you do not have an InfluxDB account, comply with the following actions.

At this moment, you must have conserved the following:

In this section, we’ll configure the ESP32 and ESP8266 boards to send out BME280 stress, moisture, as well as temperature readings to InfluxDB.

Creating an InfluxDB Account
InfluxDB select provider

Before uploading the code to your board, you require to put your network credentials, the database URL, token, company, as well as bucket name.

InfluxDB select plan

Insert the InfluxDB web server URL on the complying with lines–:

InfluxDB Cloud Getting Started Dashboard

Loading Data in InfluxDB

Note: if you’re running InfluxDB in your area on a Raspberry Pi, the URL will be the Raspberry Pi IP address on port 8086.

InfluxDB Load Dara Sources

Learn more concerning the ESP32 and also ESP8266 with our sources:

InfluxDB Load Data Arduino Client

Thanks for reading.

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

ESP32/ESP8266 Send Sensor Readings to InfluxDB

In this section, we’ll program the ESP32 and ESP8266 boards to send BME280 temperature, humidity, and pressure readings to InfluxDB.

Parts Required

For this project, you need the following parts*:

  • or board (read );
  • or any other sensor you’re familiar with;
  • ;       
  • .

* you can also test the project with random values instead of sensor readings, or you can use any other sensor you’re familiar with.

You can use the preceding links or go directly to to find all the parts for your projects at the best price!

Schematic Diagram

In this tutorial, we’ll send BME280 sensor readings to InfluxDB. So, you need to wire the BME280 sensor to your board. Follow one of the next schematic diagrams.

ESP32 with BME280

We’re going to use I2C communication with the BME280 sensor module. Wire the sensor to the default ESP32 SCL (GPIO 22) and SDA (GPIO 21) pins, as shown in the following schematic diagram.

ESP32 BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

Not familiar with the BME280 with the ESP32? Read this tutorial: .

ESP8266 with BME280

We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the ESP8266 SDA (GPIO 4) and SCL (GPIO 5) pins, as shown in the following schematic diagram.

ESP8266 NodeMCU BME280 Sensor Temperature Humidity Pressure Wiring Diagram Circuit

Not familiar with the BME280 with the ESP8266? Read this tutorial: .

Installing Libraries

For this project, you need to install the following libraries:

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 and ESP32 Boards version 2.0.1 Check your boards’ version in Tools > Board > Boards Manager. Then, search for ESP8266 or ESP32 and upgrade to one of those versions. (I found some issues with the newest 3.0.2 and 2.0.2 versions)

  1. Follow the same instructions to install the Adafruit BME280 Library and Adafruit Unified Sensor Library.

Installation – VS Code

If you’re using VS Code with the PlatformIO extension, start by creating an Arduino project for your ESP32 or ESP8266 board.

Then, click on the PIO Home icon and then select the Libraries tab. Search for “influxdb“. Select the ESP8266 Influxdb by Tobias Schürg.

Install InfluxDB library VS Code

Follow the same procedure for the Adafruit BME280 library and Adafruit Unified Sensor library.

Your plaformio.ini file should look as follows (we also added a line to change the Serial Monitor baud rate to 115200).

monitor_speed = 115200
lib_deps = 
	tobiasschuerg/ESP8266 Influxdb@^3.12.0
	adafruit/Adafruit BME280 Library@^2.2.2
	adafruit/Adafruit Unified Sensor@^1.1.5

Send Sensor Readings to InfluxDB—Code

Copy the following code to the Arduino IDE or to the main.cpp file if you’re using VS Code with the PlatformIO extension. The code is compatible with both the ESP32 and ESP8266 boards.

This code is based . We made a few modifications to include the BME280 sensor readings.

/*
  Rui Santos
  Complete project details at our blog: https://RandomNerdTutorials.com/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
// Based on this library example: https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/blob/master/examples/SecureBatchWrite/SecureBatchWrite.ino

#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#if defined(ESP32)
  #include <WiFiMulti.h>
  WiFiMulti wifiMulti;
  #define DEVICE "ESP32"
#elif defined(ESP8266)
  #include <ESP8266WiFiMulti.h>
  ESP8266WiFiMulti wifiMulti;
  #define DEVICE "ESP8266"
  #define WIFI_AUTH_OPEN ENC_TYPE_NONE
#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 authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "REPLACE_WITH_YOUR_TOKEN"
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
#define INFLUXDB_ORG "REPLACE_WITH_YOUR_ORG"
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
#define INFLUXDB_BUCKET "SENSOR"
// 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 sensorReadings("measurements");

//BME280
Adafruit_BME280 bme; // I2C

float temperature;
float humidity;
float pressure;

// Initialize BME280
void initBME(){
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

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();
  
  //Init BME280 sensor
  initBME();
  
  // Add tags
  sensorReadings.addTag("device", DEVICE);
  sensorReadings.addTag("location", "office");
  sensorReadings.addTag("sensor", "bme280");

  // 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() {
  // Get latest sensor readings
  temperature = bme.readTemperature();
  humidity = bme.readHumidity();
  pressure = bme.readPressure()/100.0F;

  // Add readings as fields to point
  sensorReadings.addField("temperature", temperature);
  sensorReadings.addField("humidity", humidity);
  sensorReadings.addField("pressure", pressure);

  // Print what are we exactly writing
  Serial.print("Writing: ");
  Serial.println(client.pointToLineProtocol(sensorReadings));
  
  // Write point into buffer
  client.writePoint(sensorReadings);

  // Clear fields for next usage. Tags remain the same.
  sensorReadings.clearFields();

  // If no Wifi signal, try to reconnect it
  if (wifiMulti.run() != WL_CONNECTED) {
    Serial.println("Wifi connection lost");
  }

  // Wait 10s
  Serial.println("Wait 10s");
  delay(10000);
}

Before uploading the code to your board, you need to insert your network credentials, the database URL, token, organization, and bucket name. Also, don’t forget to insert your timezone. in the right format.

How the Code Works

Start by including the required libraries and setting the DEVICE name accordingly to the selected board (ESP32 or ESP8266).

#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

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

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

Insert your network credentials on the following variables so that the ESP32 or ESP8266 boards can connect to the internet using your local network.

// 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—:

// 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—:

#define INFLUXDB_TOKEN "REPLACE_WITH_YOUR_INFLUXDB_TOKEN"

Add your InfluxDB organization name—.

#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 . The easiest way is to . 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—.

InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);

Point

Then, we create a Point instance called sensorReadings. The point will be called measurements on the database. Later in the code, we can refer to that point (sensorReadings) to add tags and fields.

Point sensorReadings("measurements");

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.

BME280 Variables

Create an Adafruit_BME280 instance called bme on the default ESP I2C pins.

Adafruit_BME280 bme; // I2C

Create variables to save the temperature, humidity, and pressure readings.

float temperature;
float humidity;
float pressure;

initBME() function

The initBME() function initializes the BME280 sensor. We’ll call it later in the setup() to initialize the sensor.

// Initialize BME280
void initBME(){
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

setup()

In the setup(), initialize the Serial Monitor for debugging purposes.

Serial.begin(115200);

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

Call the initBME() function to initialize the BME280 sensor.

//Init BME280 sensor
initBME();

Add tags to your data using addTag(). We’re adding the device name, the name of the sensor, and the location of the sensor. You may add other tags that might be useful for your specific project.

sensorReadings.addTag("device", DEVICE);
sensorReadings.addTag("location", "office");
sensorReadings.addTag("sensor", "bme280");

Synchronize time, which is necessary for certificate validation.

timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");

Check the connection to the InfluxDB server and print any error messages in case the connection fails:

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

loop()

In the loop(), we’ll send the sensor readings to InfluxDB every 10 seconds.

We get temperature, humidity, and pressure readings:

temperature = bme.readTemperature();
humidity = bme.readHumidity();
pressure = bme.readPressure()/100.0F;

And we add those readings as fields to our point (database data row).

// Add readings as fields to point
sensorReadings.addField("temperature", temperature);
sensorReadings.addField("humidity", humidity);
sensorReadings.addField("pressure", pressure);

Print in the Serial Monitor what we’re writing to the point:

Serial.println(client.pointToLineProtocol(sensorReadings));

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

client.writePoint(sensorReadings);

Clear the fields to be ready for usage in the next loop.

sensorReadings.clearFields();

New data is written to the database every 10 seconds.

Serial.println("Wait 10s");
delay(10000);

Demonstration—Visualizing your Data

After inserting all the required settings on the code, you can upload it to your ESP32/ESP8266 board. If you get any error during compilation, check the following:

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

ESP Send BME280 Sensor Readings to InfluxDB

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 measurement under the _measurement field, the device and the location. Then, you can select the temperature, humidity, or pressure values. You can also select all readings if you want to plot them all on the same chart.

After making the query, 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. You can also click on the CUSTOMIZE button to change the color of the series.

ESP32 ESP8266 Data Explorer InfluxDB

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. For example, multiple charts to show temperature, humidity, and pressure, and boxes to show the current measurements.

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, Office Temperature(ESP32). You can also click on the Customize button to customize the graph (we suggest selecting different colors for temperature, humidity, and pressure). Finally, click on the icon in the top right corner to add the visualization as a cell to your dashboard.

InfluxDB ESP Temperature Dashboard cell

Repeat the same process for the other readings (humidity, and pressure). You can also add a single stat to show the current values of each reading.

I have the ESP32 and ESP8266 running the same code simultaneously, so I created a dashboard that shows the readings of each board.

ESP32 ESP8266 Sensor Readings Dashboard InfluxDB

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

Wrapping Up

In this tutorial, you learned how to send multiple sensor readings to InfluxDB. InfluxDB adds a timestamp to all data rows (point).

As an example, we used a BME280 sensor, but you can easily modify the example to use any other sensor or add more sensors. You can also run this example on multiple boards to monitor the temperature, humidity, and pressure in different places—don’t forget to add different tags to identify the places or the boards.

We hope you found this tutorial useful. What other projects would you like to see using InfluxDB? Let us know in the comments section.

Learn more about the ESP32 and ESP8266 with our resources:

Thanks for reading.