MQ135

Wiring a MQ135 sensor to an ESP32 microcontroller

Connect the 5V (also called VCC) pin of the sensor with the 5V pin of the microcontroller, the GND pin with the GND pin, and the sensor’s AO pin (analog pin) with any of the ESP32‘s ADC pin (I used pin number 34).
You can see on the diagram below that I crossed one pin. That’s DO (digital pin), which you don’t need to wire to the microcontroller.

Wiring diagram of MQ135

Testing MQ135 sensor

Download the library for the sensor. Upload the library to the microcontroller via ampy.

MQ135 lib

When you’re done with the uploading of the library, close the terminal, and connect to the microcontroller via MobaXTerm, as we’ve done earlier.

In the terminal that is visible after the establishment of the connection, run the following commands:

1from mq135 import MQ135 
2from machine import Pin 
3from dht import DHT11 
4mq135 = MQ135(Pin(36)) - #If you connected sensor’s AO pin with the different microcontroller’s ADC pin, change the number of pin inside the brackets with this pin.
5mq135.get_rzero() - #Call this function continuously for a couple of minutes to calibrate the sensor, otherwise it won't work properly.

Open your library in the code editor, and write the last value obtained from the get_rzero() function in line 20 of the library, then save the change.

Using ampy, upload the updated library to the microcontroller. When uploading the updated library, the old version of the library will be automatically changed with the updated one.
Now you can use your sensor normally.

To have a more precise measurement of the air quality, we will provide the temperature and the humidity, measured by the DHT11 sensor, to our air quality sensor.

1dht_sensor = DHT11(Pin(16)) - #remember to which GPI pin of the microcontroller you connected DHT11’s DATA pin
2dht_sensor.measure()
3temperature, humidity = dht_sensor.temperature(), dht_sensor.humidity()
4mq135.get_corrected_ppm(temperature, humidity)

After the last command is run, in the next line you should see the number, which indicates the ppm of the CO2, measured in the air.

Info

PPM stands for "parts per million." It is a way to measure how much of one substance is mixed into another. In the context of air particles, PPM tells us how many tiny particles, like dust, pollutants, or gases, are present in every million air particle.
PPM helps us understand how clean or polluted the air is. Higher PPM means more particles are floating around, which could be harmful to breathe.
MQ135 testing