DIY Air Quality Sensor: Build with ESP8266 and InfluxDB 2

DIY Air Quality Sensor: Build with ESP8266 and InfluxDB

If you’re a DIY enthusiast who enjoys tinkering with smart devices, this project will guide you in building a real-time air quality monitoring system. We’ll use an ESP8266 microcontroller (version 3.0.2) along with the DHT22 and MQ135 sensors to measure temperature, humidity, and gas concentration. The sensor data will be sent securely to an InfluxDB time-series database (InfluxDBClient version 3.13.2).

This project is perfect for those looking to get started with Internet of Things (IoT) projects while using reliable libraries and tools to ensure smooth performance. By using the DIY air quality sensor, you can monitor your environment in real-time.”

Key Components:

  • ESP8266 (NodeMCU) (Version 3.0.2): A WiFi-enabled microcontroller perfect for IoT projects.
  • DHT22 Sensor: Measures temperature and humidity.
  • MQ135 Sensor: Detects air quality and gas concentration (e.g., CO2).
  • InfluxDB: A time-series database used to store and visualize sensor data.
  • WiFiClientSecure: Ensures secure communication with InfluxDB via HTTPS.

Setting Up the Required Libraries

Before getting started, ensure that you have installed the correct versions of the required libraries:

  • ESP8266 Version 3.0.2: This version ensures better compatibility with the InfluxDBClient and your ESP8266 hardware.
  • InfluxDBClient Version 3.13.2: This specific version works smoothly with the ESP8266 library for sending data to InfluxDB via HTTPS.


You can install these libraries via the Arduino Library Manager:

  1. Go to Sketch > Include Library > Manage Libraries.
  2. Search for ESP8266 and install version 3.0.2.
  3. Search for InfluxDBClient and install version 3.13.2.

Setting Up the Code

Once the correct libraries are in place, let’s dive into the code that will get your air quality monitoring system up and running.

#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecure.h>   // Include WiFiClientSecure for HTTPS
#include <InfluxDbClient.h>
#include "MQ135.h"
#include "DHTesp.h"

#define ANALOGPIN A0

// WiFi credentials
#define ssid "ssid"
#define password "yourssidpass"

// INFLUXDB AREA
#define INFLUXDB_URL "http://influxdb2.example.com"
#define INFLUXDB_ORG "my-org"
#define INFLUXDB_BUCKET "bucket"
#define INFLUXDB_TOKEN "tokenhere"

// Declare WiFiClientSecure
WiFiClientSecure espClient;

// InfluxDB client using HTTPS and token-based auth
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
Point sensor("gassensor");

DHTesp dht;
MQ135 gasSensor(ANALOGPIN);
unsigned long lastSend;

void setup() {
  Serial.begin(9600);
  dht.setup(14, DHTesp::DHT22);
  pinMode(LED_BUILTIN, OUTPUT);
  delay(10);
  Serial.println('\n');

  // Connect to WiFi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());

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

  // Optional: Disable SSL certificate verification for testing
  // espClient.setInsecure(); // Disable SSL validation (not recommended for production)

  // Add a tag to the InfluxDB point
  sensor.addTag("tag", "iot");
}

void sendDataCollection() {
  // Collect DHT22 sensor data
  float humidity = dht.getHumidity();
  float temperature = dht.getTemperature();
  float heatIndex = dht.computeHeatIndex(temperature, humidity);
  float dewPoint = dht.computeDewPoint(temperature, humidity);

  // Collect MQ135 gas sensor data
  float rzero = gasSensor.getRZero();
  float correctedPPM = gasSensor.getCorrectedPPM(temperature, humidity);

  // Add data fields to InfluxDB point
  sensor.clearFields();
  sensor.addField("mq135_rzero", rzero);
  sensor.addField("temperature", temperature);
  sensor.addField("humidity", humidity);
  sensor.addField("dewPoint", dewPoint);
  sensor.addField("heatIndex", heatIndex);

  // Print collected data for debugging
  Serial.print("CO2 ppm value: ");
  Serial.println(correctedPPM);
  Serial.print("Temperature value: ");
  Serial.println(temperature);
  Serial.print("Humidity value: ");
  Serial.println(humidity);

  // Send data to InfluxDB
  if (!client.writePoint(sensor)) {
    Serial.print("InfluxDB write failed: ");
    Serial.println(client.getLastErrorMessage());
  } else {
    Serial.println("Data successfully written to InfluxDB");
  }
}

void loop() {
  if (millis() - lastSend > 10000) {
    sendDataCollection();
    lastSend = millis();
  }

  // Blinking LED to indicate running status
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(2000);
}

Breakdown of the Code

1. WiFi and InfluxDB Setup

We start by connecting the ESP8266 to your WiFi network. The WiFi credentials are defined at the top of the code, and the ESP8266 connects in setup(). After connecting to WiFi, the code attempts to connect to the InfluxDB instance using HTTPS.

2. Sensor Data Collection

We use the DHT22 sensor to measure temperature and humidity, and the MQ135 sensor to detect gas levels (e.g., CO2). The data from both sensors is then prepared for sending to InfluxDB:

sensor.addField("temperature", temperature);
sensor.addField("humidity", humidity);
sensor.addField("mq135_rzero", rzero);

3. Sending Data to InfluxDB

The sensor data is sent to the InfluxDB database every 10 seconds in the loop() function using the writePoint() method of the InfluxDB client. If the write fails, an error message is printed to the serial monitor.

Visualizing Data with InfluxDB

Once your data is stored in InfluxDB, you can use visualization tools like Grafana to create real-time dashboards. This will allow you to monitor your air quality, temperature, and humidity trends.

Conclusion

With ESP8266 version 3.0.2 and InfluxDBClient version 3.13.2, you can reliably build an IoT system for air quality monitoring. This setup is perfect for DIY enthusiasts who want to explore smart home projects or environmental monitoring. By integrating InfluxDB, you also gain powerful tools to track and visualize sensor data over time.

If you’re interested in my previous post where I used InfluxDB 1, you can find it here.

Give it a try, and happy building!

Leave a Comment