Thursday, March 28, 2024
Data AnalyticsHow ToSensorsTutorials/DIY

Using Mq135 Sensor with InfluxDB

Today in this tutorial we learn How to Using Mq135 Sensor with InfluxDB for measure air quality. MQ135 Sensor formally known as Gas Sensor and stored data into InfluxDB.

InfluxDB is an open-source time series database (TSDB) developed by InfluxData. It is written in Go and optimized for fast, high-availability storage and retrieval of time series data in fields such as operations monitoring, application metrics, Internet of Things sensor data, and real-time analytics.

Visit this : InfluxDB | Installation | How To Use | Time Series Database ?

Requirement :

  • MQ135 Senor
  • Esp8266/NodeMCU
  • Arduino IDE
  • Influx DB
  • NodeJS
  • MQTT Broker

Visit this article for install Nodejs – How To Install Node.js on Ubuntu

Visit this article for install InFluxDb –How to Install InfluxDB on Ubuntu and Getting Started with InfluxDB

We use test.osquitto.org for MQTT broker but if you are intrested in your own secure mqtt broker, visit this article – How To Create Secure MQTT Broker

Using Mq135 Sensor with InfluxDB

Here a NodeJS code, run this code on a system where you want to stored sensor data. After run this code you can received sensor data from NodeMCU and stored in the InfluxDB Database.

Data.js code (this code run on System where you want to stored data)

**********************************data.js*****************************************

var mqtt = require('mqtt');
const fs = require('fs');
//var obj = { 'username': 'user', 'password': 'password' }
var client = mqtt.connect('mqtt://test.mosquitto.org:1883');
//var client = mqtt.connect('mqtt://test.mosquitto.org:1883', obj);
const Influx = require('influxdb-nodejs');
const clientInflux = new Influx('http://127.0.0.1:8086/aqDB');
const fieldSchema = {
aq: 'i',
ppm:'f'
};
const tagSchema = {
deviceId:'*'
};
clientInflux.schema('sendData', fieldSchema, tagSchema, {
// default is false
stripUnknown: true,
});

client.on('connect', () => {
console.log('Connected to server');
client.subscribe('sendData');
});
client.on('close', () => {
console.log('Disconnected from server');
});

client.on('message', (topic, message) => {
console.log("mqtt msg : " + message.toString());
data = JSON.parse(message)
if (data.deviceId && data.data) {
clientInflux.write('airData')
.tag({
deviceId: data.deviceId,
})
.field({
aq: data.data.rzero,
ppm:data.data.ppm
})
.then(() => {
console.log("Success")
})
.catch((err)=>{
console.log(err)
});
}
else
{
console.log("")
}
});

*****************************data.js***************************************

Node Sensor Code “mq135.ino”

Flash this Arduino sketch code in ESP8266/NodeMCU using Arduino IDE. If you don’t know visit this article – Arduino Support for ESP8266 with simple test code

*********************************Mq135.js*********************************

#include <ESP8266WiFi.h>
#include <MQ135.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define ANALOGPIN A0

const char* ssid = "enter ssid";
const char* password = "enter password";

const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
//const char* mqttUser = "user";
//const char* mqttPassword = "password";

WiFiClient espClient;
PubSubClient client(espClient);


MQ135 gasSensor = MQ135(ANALOGPIN);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(100);
pinMode(2, OUTPUT);
// WiFi.softAP(hostssid, hostpassword);/
Serial.println();
WiFi.begin(ssid, password);
int i = 0;
while ( (i <= 10) && (WiFi.status() != WL_CONNECTED) )
{
delay(500);
Serial.print(".");
i++;
}
Serial.println();
// WiFi.config(ip,gateway,subnet,dns);
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

client.setServer(mqttServer, mqttPort);
client.setCallback(callback);

while (!client.connected()) {
Serial.println("Connecting to MQTT...");

if (client.connect("ESP8266Client1")) {

Serial.println("connected");

} else {

Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);

}
}

client.publish("sendData", "Hello from ESP8266");
client.subscribe("sendData");

}

void callback(char* topic, byte* payload, unsigned int length) {

Serial.print("Message arrived in topic: ");
Serial.println(topic);

Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}

Serial.println();
Serial.println("-----------------------");

}

void loop() {
// put your main code here, to run repeatedly:
float rzero = gasSensor.getRZero(); //this to get the rzero value, uncomment this to get ppm value
Serial.print("RZero=");
Serial.println(rzero); // this to display the rzero value continuously, uncomment this to get ppm value

float ppm = gasSensor.getPPM(); // this to get ppm value, uncomment this to get rzero value
Serial.print("PPM=");
Serial.println(ppm); // this to display the ppm value continuously, uncomment this to get rzero value
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["ppm"] = ppm;
String d;
json.printTo(d);
client.publish("sendData", d.c_str());
Serial.println(d);
digitalWrite(2, HIGH);
delay(500);
digitalWrite(2, LOW);
delay(500);
}

*********************************mq135******************************

Pin Diagram for Mq135 sensor

mq135                                esp82266

VCC       ============> 3.3v

GND     ============>GND

DATA   ============>A0

 


Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog. Visit https://compileiot.com/ for explore Internet of Things.

We have other tutorials with ESP32 that you may find useful:

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

7 thoughts on “Using Mq135 Sensor with InfluxDB

Leave a Reply

Your email address will not be published. Required fields are marked *