Connect MQ135 Air Quality Sensor and ESP32 to the Cloud over MQTT

Air Quality is deteriorating day by day and Air pollution has become a common phenomenon everywhere. Specially in the urban areas, the inevitable increase in industries and urbanization would add up to make it worse.

The MQ135 Gas sensors are used in air quality control systems and are suitable for detecting gases such as CO2,  Smoke, NH3, NOx, Alcohol, Benzene, etc.

The purpose of this tutorial is to explain how to develop a device which can monitor the pollutant parameters in Air, especially CO2 in real time using MQ135 Gas Sensor with ESP32 WiFi module to send the data to AskSensors IoT platform.

1) Prerequisites :

Followings are the prerequisites and backgrounds you need to completely understand this tutorial and monitor the Air Quality with AskSensors IoT cloud.

  • AskSensors account is required. Get your subscription here.
  • Create a new sensor device with at least one module to connect your Gas sensor.
  • Now after this click on ‘Add graph and select the graph type you prefer to show the measurements.
  • Copy down your sensor API KEY IN, we will use it later.

2) Required Materials 

  • Computer running Arduino IDE software.
  • ESP32 development board.
  • MQ135 Gas Sensor.
  • 1K Resistor.
  • Jumper wires.
  • USB micro cable to connect ESP32 development board to the computer.

3) MQ135 Features

  • Some of the MQ135 sensor characteristics are listed below:
    • Operating Voltage is +5V.
    • Output voltage: Analog 0V to 5V or Digital 5V  TTL Logic.
    • Preheat duration 20 seconds.
    • Fast response and High sensitivity.
  • We can either use the digital pin or the analog pin to get indication of the PPM (Parts-per-million) of specific gas in Air. The digital Output (5V  TTL Logic) gives only good or bad status by setting a threshold value using the potentiometer onboard, While the Analog output gives the raw data measurements.
  • In this tutorial we use the analog output : The ESP32 reads the analog pin A0 (0-5V) that are directly proportional to the concentration of the CO2 gas detected by the sensor.
  • Here are some example of indicator levels to read the CO2 PPM values:
    • Less than 400 PPM: Normal background concentration in outdoor ambient Air.
    • From 400 to 1000 PPM: Typical in occupied indoor spaces with good air exchange.
    • More than 1000 PPM: Poor air.
  • Notes:
    • In order to get accurate PPM data, you will need to calibrate the sensor as explained by David Gironi.
    • For high performances CO2 sensor, the MG811 is recommended. The MQ135 is a cheap sensor and not recommended for specific applications that may put lifes in danger.

4) Circuit schematic

The connections are pretty simple. The picture below shows the MQ135 Gas Sensor connected to the ESP32 development board.

  • The MQ135 sensor is a 4-pin module. Connect the MQ135Vcc pin to the 5V of the ESP32 board.
  • Connect the ground pin of the MQ135 to the ESP32 ground.
  • Connect the Analog pin of the MQ135 to the A0 pin of the ESP32 via a 1K resistor.

Note: The ESP32 GPIOs require 3V3 signals (not 5V tolerent). For quick hack, you can only add a serial resistor of 1K between the MQ135 Analog pin and the ESP32 A0 pin to protect the ESP32 GPIOs from damage. However, for production, a 5V/3V3 level shifter is needed to guarantee long term circuit reliability. You can check this page to get a 5V/3V3 level shifter module.

  • Last, connect your ESP32 to the computer through a USB cable. The ESP32 will be powered from the USB 5V.

5) Install the ESP32 in Arduino IDE

The ESP32 will be programmed using Arduino IDE. There’s an add-on for the Arduino IDE (1.8.7 or higher) that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow the instructions below:

  • Open the preferences window from the Arduino IDE : File> Preferences.
  • Go to the “Additional Board Manager URLs” field, Enter the following URL:

https://dl.espressif.com/dl/package_esp32_index.json

  • If you already have the ESP8266 boards URL, separate the URLs with a comma as shown below:

https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.jso

  • Open boards manager (Tools > Board > Boards Manager), search for ESP32 and click the install button for the “ESP32 by Espressif Systems”.

6) Download the libraries

  • The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT.

o Download the PubSubClient library from github.

o Unzip the .zip folder and you should get pubsubclient-master folder.

o Rename your folder from pubsubclient-master to pubsubclient.

o Move the pubsubclient folder to your Arduino IDE installation libraries folder.

o Then, re-open your Arduino IDE.

The library comes with a number of example sketches that are not fully compatible with the ESP32. However, the example provided in this tutorial is working very reliably in the Arduino IDE software.

  • The AskSensors MQTT Publish/Subscribe API is described in detail in this guide.

7) Write the code:

Now let’s write the code. Download this complete demo from the AskSensors github page. You need to edit the following parameters.

const char* ssid = ".................."; // Wifi SSID
const char* password = ".................."; // Wifi Password 
const char* username = "................."; // my AskSensors username 
const char* pubTopic = "publish/..../....."; // publish/username/apiKeyIn 
const unsigned int writeInterval = 25000; // write interval (in ms)
 

8) Run the test:

  • Connect your ESP32 board to your computer through the micro-USB cable. Make sure the power LED goes high on the module to ensure power supply.
  • Open your arduino IDE and select Tools options for your ESP32 board type and serial port where it’s connected then click upload. The code will be running automatically after Reset.
  • Open the serial terminal to supervise the ESP32 software sequence step by step.
  • Now, we will return back to the AskSensors web application to monitor the PPM measurements sent by the ESP32.

gauge-Air-quality-esp32-mqtt-iot-platform

9) Source code

A basic source code is shown below. Please refer to the AskSensors Github page to get the latest version and updates.

/*
* Description: Air Qualiy Monitoring using ESP32 & MQ-135 connected to AskSensors over MQTT
* Author: https://asksensors.com, 2020
* github: https://github.com/asksensors
*/
#include <WiFi.h>
#include <PubSubClient.h>
//TODO: ESP32 MQTT user config
const char* ssid = “………………“; // Wifi SSID
const char* password = “………………“; // Wifi Password
const char* username = “……………..“; // my AskSensors username
const char* pubTopic = “publish/…./…..“; // publish/username/apiKeyIn
const unsigned int writeInterval = 25000; // write interval (in ms)
//AskSensors MQTT config
const char* mqtt_server = “mqtt.asksensors.com“;
unsigned int mqtt_port = 1883;
#define MQ135_THRESHOLD_1 1000 // Fresh Air threshold
WiFiClient askClient;
PubSubClient client(askClient);
void setup() {
Serial.begin(115200);
Serial.println(“*****************************************************“);
Serial.println(“********** Program Start : ESP32 publishes MQ-135n data to AskSensors over MQTT“);
Serial.print(“********** connecting to WIFI : “);
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.“);
}
Serial.println(““);
Serial.println(“->WiFi connected“);
Serial.println(“->IP address: “);
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected())
reconnect();
client.loop();
int MQ135_data = analogRead(A0);
if(MQ135_data < MQ135_THRESHOLD_1){
Serial.print(“Fresh Air: “);
} else {
Serial.print(“Poor Air: “);
}
Serial.print(MQ135_data); // analog data
Serial.println(“ PPM“); // Unit = part per million
Serial.println(“********** Publish MQTT data to ASKSENSORS“);
char mqtt_payload[30] = ““;
snprintf (mqtt_payload, 30, “m1=%ld“, MQ135_data);
Serial.print(“Publish message: “);
Serial.println(mqtt_payload);
client.publish(pubTopic, mqtt_payload);
Serial.println(“> MQTT data published“);
Serial.println(“********** End “);
Serial.println(“*****************************************************“);
delay(writeInterval);// delay
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(“********** Attempting MQTT connection…“);
// Attempt to connect
if (client.connect(“ESP32Client“, username, ““)) {
Serial.println(“-> MQTT client connected“);
} else {
Serial.print(“failed, rc=“);
Serial.print(client.state());
Serial.println(“-> try again in 5 seconds“);
// Wait 5 seconds before retrying
delay(5000);
}
}

}

 

What’s next?

In this tutorial we explained how to simply connect the MQ135 Gas to the AskSensors cloud.

Now that you have got the basics, you can try connecting other sensors to the AskSensors IoT cloud. You can start with this list of tutorials. Feel free to comment if you have any questions about this tutorial.

We will be happy to hear your thoughts

      Leave a reply