ESP32 Air Quality Monitor with PMS5003, BME280, MQ-135, OLED & Web Dashboard

Build an ESP32 air quality monitor with a PMS5003 dust sensor, BME280, MQ-135, OLED, RGB AQI LED, buzzer and a live Wi-Fi dashboard. Wiring table, diagram and full code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUESP32 DevKit
  • Parts11 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 air quality monitor measures the fine dust you breathe (PM1.0, PM2.5 and PM10) with a Plantower PMS5003 laser sensor, adds temperature, humidity and pressure from a BME280, and a general gas level from an MQ-135. It works out an AQI value for PM2.5 using the Indian National AQI bands, shows everything on a 0.96 inch OLED, lights an RGB LED from green to red, beeps when the air turns poor, and serves a live dashboard you can open on any phone on your Wi-Fi.

It is a big, multi-sensor IoT build that combines UART, I2C, ADC and PWM on one board. It is useful for bedrooms, classrooms, workshops, and for checking how well an air purifier works during winter smog.

ESP32 air quality monitor with PMS5003, BME280, MQ-135, SSD1306 OLED, RGB LED and buzzer

How It Works

  • PMS5003 dust sensor: a small fan pulls air through a laser beam. Light scattered by particles is counted and the sensor sends a 32-byte frame every second over serial at 9600 baud. The ESP32 reads it on UART2 (GPIO16/17), checks the checksum and takes the atmospheric PM1.0, PM2.5 and PM10 values in µg/m³.
  • AQI calculation: the PM2.5 value is converted with the Indian NAQI breakpoints (0-30 Good, 31-60 Satisfactory, 61-90 Moderate, 91-120 Poor, 121-250 Very Poor, above 250 Severe). The official AQI uses 24-hour averages, so the live number is a guide, not a certified reading.
  • BME280: reports temperature, relative humidity and air pressure over I2C on the same bus as the OLED (GPIO21 SDA, GPIO22 SCL).
  • MQ-135: its heater runs on 5V and the analog output rises when gases such as smoke, alcohol or ammonia are present. A 10k/20k divider keeps the signal below 3.3V for GPIO34. The value is shown as a raw relative level, because the MQ-135 is not accurate enough for real ppm readings without calibration.
  • Status outputs: the RGB LED shows the AQI colour (purple means no data from the PMS5003 for 10 seconds). Above AQI 200 the buzzer gives a short beep once a minute through a BC547 transistor.
  • Web dashboard: the ESP32 joins your Wi-Fi and serves a page at its IP address. The page fetches /data as JSON every 3 seconds, so the cards update without reloading.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • Plantower PMS5003 particulate sensor with its 8-pin cable (or an adapter board) – 1
  • BME280 temperature, humidity and pressure module (I2C) – 1
  • MQ-135 air quality sensor module – 1
  • 0.96 inch SSD1306 I2C OLED, 128×64 – 1
  • Common-cathode RGB LED (5 mm) – 1
  • Active 5V buzzer – 1
  • BC547 NPN transistor – 1
  • Resistors: 220 Ω – 3, 1k – 1, 10k – 1, 20k – 1
  • 5V 2A USB adapter and cable – 1
  • Breadboard or perfboard and jumper wires

Wiring Table

Module pinESP32 pinNotes
PMS5003 pin 1 (VCC)VIN (5V)The fan needs 5V; logic is 3.3V so it connects directly
PMS5003 pin 2 (GND)GND
PMS5003 pin 3 (SET)GPIO4HIGH keeps the sensor running
PMS5003 pin 4 (RX)GPIO17 (TX2)
PMS5003 pin 5 (TX)GPIO16 (RX2)
PMS5003 pins 6, 7, 8Not connectedRESET has an internal pull-up
BME280 VIN / GND3V3 / GND
BME280 SDA / SCLGPIO21 / GPIO22I2C address 0x76 (0x77 also tried)
OLED VCC / GND3V3 / GND
OLED SDA / SCLGPIO21 / GPIO22Shared I2C bus, address 0x3C
MQ-135 VCC / GNDVIN (5V) / GNDLet it warm up for 24 hours the first time
MQ-135 AOGPIO34 via 10k20k from GPIO34 to GND (divider)
RGB LED red / green / blueGPIO25 / GPIO26 / GPIO27220 Ω on each leg
RGB LED cathodeGNDLongest leg
BC547 baseGPIO33 via 1kEmitter to GND
Buzzer +5VBuzzer – to BC547 collector

Connection Diagram

The illustration above shows the general layout; its wire routes are only for orientation. The pin-accurate drawing below matches the wiring table exactly, so follow it while building.

ESP32 Air Quality Monitor – Pin-Accurate Wiring Power USB 5V: ESP32 VIN feeds PMS5003 pin 1 (VCC 5V) and MQ-135 VCC ESP32 GND: common ground for every module PMS5003 Pin 2 GND to GND, pin 3 SET to GPIO4 Pin 4 RX to GPIO17 (TX2), pin 5 TX to GPIO16 (RX2) Pins 6 RESET and 7, 8 NC: leave unconnected BME280 VIN to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x76) SSD1306 OLED VCC to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x3C) MQ-135 VCC to 5V (VIN), GND to GND AO through 10k to GPIO34, 20k from GPIO34 to GND RGB LED Red to GPIO25, green to GPIO26, blue to GPIO27, each via 220 Ω Common cathode (longest leg) to GND Buzzer GPIO33 via 1k to BC547 base, emitter to GND Buzzer + to 5V, buzzer – to BC547 collector
Pin-accurate connection diagram for the ESP32 air quality monitor.

Code

Install the ESP32 board package in the Arduino IDE and choose ESP32 Dev Module. From the Library Manager install Adafruit BME280, Adafruit Unified Sensor, Adafruit SSD1306 and Adafruit GFX. The PMS5003 is read directly, so it needs no library. Replace the Wi-Fi placeholders with your own network name and password, upload, and open the Serial Monitor at 115200 baud to see the dashboard address.

/*
  ESP32 Air Quality Monitor
  PMS5003 (PM1.0 / PM2.5 / PM10) + BME280 (temperature, humidity, pressure)
  + MQ-135 (relative gas level) + SSD1306 OLED + RGB status LED + buzzer
  + Wi-Fi web dashboard with live JSON data.

  Board: ESP32 Dev Module (ESP32 DevKit V1)
  Libraries: Adafruit BME280, Adafruit Unified Sensor, Adafruit SSD1306, Adafruit GFX
  The PMS5003 is read directly over UART2 (no extra library needed).
*/

#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_BME280.h>

// ---------- User settings ----------
const char* WIFI_SSID     = "YOUR_WIFI_SSID";      // placeholder: put your Wi-Fi name
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";  // placeholder: put your Wi-Fi password

// ---------- Pins ----------
#define PMS_RX_PIN   16   // ESP32 RX2  <- PMS5003 TX (pin 5)
#define PMS_TX_PIN   17   // ESP32 TX2  -> PMS5003 RX (pin 4)
#define PMS_SET_PIN  4    // HIGH = sensor running, LOW = sleep (fan off)
#define MQ135_PIN    34   // MQ-135 AO through a 10k/20k divider (ADC1, input only)
#define LED_R_PIN    25   // RGB LED red   (through 220 ohm)
#define LED_G_PIN    26   // RGB LED green (through 220 ohm)
#define LED_B_PIN    27   // RGB LED blue  (through 220 ohm)
#define BUZZER_PIN   33   // Active buzzer via BC547 transistor
// I2C: SDA = GPIO21, SCL = GPIO22 (BME280 at 0x76, OLED at 0x3C)

// ---------- Objects ----------
Adafruit_SSD1306 display(128, 64, &Wire, -1);
Adafruit_BME280 bme;
WebServer server(80);
HardwareSerial pmsSerial(2);

// ---------- Readings ----------
struct Readings {
  uint16_t pm1 = 0, pm25 = 0, pm10 = 0;
  float tempC = NAN, hum = NAN, pressHpa = NAN;
  int gasRaw = 0;          // 0-4095 relative gas level from MQ-135
  int aqi = 0;             // India NAQI sub-index for PM2.5
  bool pmsOk = false;
} r;

bool bmeOk = false;
unsigned long lastPmsFrame = 0;
unsigned long lastScreen = 0;
unsigned long lastBeep = 0;

// ---------- India NAQI sub-index for PM2.5 (24-h breakpoints, used here as live guide) ----------
int pm25ToAqi(float c) {
  // {C_low, C_high, I_low, I_high}
  const float bp[6][4] = {
    {0, 30, 0, 50}, {31, 60, 51, 100}, {61, 90, 101, 200},
    {91, 120, 201, 300}, {121, 250, 301, 400}, {251, 500, 401, 500}
  };
  if (c > 500) return 500;
  for (int i = 0; i < 6; i++) {
    if (c <= bp[i][1]) {
      if (c < bp[i][0]) c = bp[i][0];
      return (int)((bp[i][3] - bp[i][2]) / (bp[i][1] - bp[i][0]) * (c - bp[i][0]) + bp[i][2]);
    }
  }
  return 500;
}

const char* aqiLabel(int aqi) {
  if (aqi <= 50)  return "Good";
  if (aqi <= 100) return "Satisfactory";
  if (aqi <= 200) return "Moderate";
  if (aqi <= 300) return "Poor";
  if (aqi <= 400) return "Very Poor";
  return "Severe";
}

// ---------- RGB LED colour by AQI ----------
void setLed(uint8_t red, uint8_t green, uint8_t blue) {
  analogWrite(LED_R_PIN, red);
  analogWrite(LED_G_PIN, green);
  analogWrite(LED_B_PIN, blue);
}

void showAqiColour(int aqi) {
  if (aqi <= 50)       setLed(0, 255, 0);     // green
  else if (aqi <= 100) setLed(120, 255, 0);   // light green
  else if (aqi <= 200) setLed(255, 180, 0);   // yellow
  else if (aqi <= 300) setLed(255, 80, 0);    // orange
  else                 setLed(255, 0, 0);     // red
}

// ---------- PMS5003 frame reader ----------
// Frame: 0x42 0x4D, length(2), 13 data words, checksum(2) = 32 bytes total
bool readPms() {
  static uint8_t buf[32];
  static uint8_t idx = 0;
  bool gotFrame = false;

  while (pmsSerial.available()) {
    uint8_t b = pmsSerial.read();
    if (idx == 0 && b != 0x42) continue;          // wait for start byte 1
    if (idx == 1 && b != 0x4D) { idx = 0; continue; } // start byte 2
    buf[idx++] = b;
    if (idx == 32) {
      idx = 0;
      uint16_t sum = 0;
      for (int i = 0; i < 30; i++) sum += buf[i];
      uint16_t check = (buf[30] << 8) | buf[31];
      if (sum == check) {
        // Atmospheric-environment values (words 4-6) are the ones to show
        r.pm1  = (buf[10] << 8) | buf[11];
        r.pm25 = (buf[12] << 8) | buf[13];
        r.pm10 = (buf[14] << 8) | buf[15];
        r.pmsOk = true;
        gotFrame = true;
      }
    }
  }
  return gotFrame;
}

// ---------- Other sensors ----------
void readOtherSensors() {
  if (bmeOk) {
    r.tempC = bme.readTemperature();
    r.hum = bme.readHumidity();
    r.pressHpa = bme.readPressure() / 100.0F;
  }
  // Average 16 samples to smooth the MQ-135 output
  long total = 0;
  for (int i = 0; i < 16; i++) total += analogRead(MQ135_PIN);
  r.gasRaw = total / 16;
}

// ---------- OLED ----------
void drawScreen() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("AQI ");
  display.print(r.aqi);
  display.print(" ");
  display.print(aqiLabel(r.aqi));

  display.setTextSize(2);
  display.setCursor(0, 12);
  display.print("PM2.5 ");
  display.print(r.pm25);

  display.setTextSize(1);
  display.setCursor(0, 32);
  display.printf("PM1 %u  PM10 %u", r.pm1, r.pm10);
  display.setCursor(0, 42);
  if (bmeOk) display.printf("%.1fC  %.0f%%  %.0fhPa", r.tempC, r.hum, r.pressHpa);
  else display.print("BME280 not found");
  display.setCursor(0, 54);
  display.printf("Gas %d  ", r.gasRaw);
  if (WiFi.status() == WL_CONNECTED) display.print(WiFi.localIP());
  else display.print("No Wi-Fi");
  display.display();
}

// ---------- Web dashboard ----------
const char PAGE[] PROGMEM = R"HTML(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32 Air Quality</title>
<style>
body{font-family:Arial,sans-serif;background:#f4f6f8;margin:0;padding:16px;text-align:center}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;max-width:700px;margin:auto}
.card{background:#fff;border-radius:10px;padding:14px;box-shadow:0 1px 4px #0002}
.v{font-size:28px;font-weight:bold}.l{color:#666;font-size:13px}
#aqi{font-size:48px;font-weight:bold}
</style></head><body>
<h2>ESP32 Air Quality Monitor</h2>
<div class="card" style="max-width:700px;margin:0 auto 12px"><div id="aqi">--</div><div id="lab" class="l">loading</div></div>
<div class="grid">
<div class="card"><div class="v" id="pm25">--</div><div class="l">PM2.5 (ug/m3)</div></div>
<div class="card"><div class="v" id="pm10">--</div><div class="l">PM10 (ug/m3)</div></div>
<div class="card"><div class="v" id="pm1">--</div><div class="l">PM1.0 (ug/m3)</div></div>
<div class="card"><div class="v" id="t">--</div><div class="l">Temperature (C)</div></div>
<div class="card"><div class="v" id="h">--</div><div class="l">Humidity (%)</div></div>
<div class="card"><div class="v" id="p">--</div><div class="l">Pressure (hPa)</div></div>
<div class="card"><div class="v" id="g">--</div><div class="l">Gas level (MQ-135 raw)</div></div>
</div>
<script>
const col=a=>a<=50?'#2e7d32':a<=100?'#7cb342':a<=200?'#f9a825':a<=300?'#ef6c00':'#c62828';
async function up(){try{const d=await (await fetch('/data')).json();
for(const k of ['pm25','pm10','pm1','g'])document.getElementById(k).textContent=d[k];
document.getElementById('t').textContent=d.t;document.getElementById('h').textContent=d.h;
document.getElementById('p').textContent=d.p;
const a=document.getElementById('aqi');a.textContent=d.aqi;a.style.color=col(d.aqi);
document.getElementById('lab').textContent='AQI (PM2.5): '+d.label;}catch(e){}}
up();setInterval(up,3000);
</script></body></html>
)HTML";

void handleRoot() { server.send_P(200, "text/html", PAGE); }

void handleData() {
  char json[256];
  snprintf(json, sizeof(json),
    "{\"pm1\":%u,\"pm25\":%u,\"pm10\":%u,\"t\":\"%.1f\",\"h\":\"%.0f\",\"p\":\"%.0f\",\"g\":%d,\"aqi\":%d,\"label\":\"%s\"}",
    r.pm1, r.pm25, r.pm10, r.tempC, r.hum, r.pressHpa, r.gasRaw, r.aqi, aqiLabel(r.aqi));
  server.send(200, "application/json", json);
}

// ---------- Setup ----------
void setup() {
  Serial.begin(115200);

  pinMode(PMS_SET_PIN, OUTPUT);
  digitalWrite(PMS_SET_PIN, HIGH);        // keep the PMS5003 awake
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  pinMode(LED_R_PIN, OUTPUT);
  pinMode(LED_G_PIN, OUTPUT);
  pinMode(LED_B_PIN, OUTPUT);
  setLed(0, 0, 255);                      // blue while starting
  analogReadResolution(12);

  pmsSerial.begin(9600, SERIAL_8N1, PMS_RX_PIN, PMS_TX_PIN);
  Wire.begin(21, 22);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Air Quality Monitor");
  display.println("Warming up sensors...");
  display.display();

  bmeOk = bme.begin(0x76) || bme.begin(0x77);
  if (!bmeOk) Serial.println("BME280 not found, check wiring");

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) delay(250);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Dashboard: http://");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("Wi-Fi not connected, running offline");
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.begin();
}

// ---------- Loop ----------
void loop() {
  server.handleClient();

  if (readPms()) {
    lastPmsFrame = millis();
    r.aqi = pm25ToAqi(r.pm25);
    showAqiColour(r.aqi);
  }
  // No valid frame for 10 s: show purple to flag a PMS5003 problem
  if (millis() - lastPmsFrame > 10000) {
    r.pmsOk = false;
    setLed(150, 0, 255);
  }

  if (millis() - lastScreen > 2000) {
    lastScreen = millis();
    readOtherSensors();
    drawScreen();
  }

  // Short beep every 60 s while AQI is Poor (above 200)
  if (r.pmsOk && r.aqi > 200 && millis() - lastBeep > 60000) {
    lastBeep = millis();
    digitalWrite(BUZZER_PIN, HIGH);
    delay(300);
    digitalWrite(BUZZER_PIN, LOW);
  }
}

Troubleshooting

ProblemFix
LED stays purple and PM values are 0TX and RX are probably swapped. PMS5003 TX (pin 5) must go to GPIO16. Also check that SET is HIGH and the fan is spinning.
BME280 not foundCheck SDA/SCL and the address. Some purple boards are BMP280 (no humidity), which this code does not support.
OLED is blankCheck the address 0x3C and that VCC is on 3V3. Run an I2C scanner if unsure.
MQ-135 value keeps fallingNormal for a new sensor. Leave it powered for a day to burn in, then note the clean-air value as your baseline.
PM readings jump in humid weatherAbove about 85% humidity water droplets are counted as dust. Compare with the BME280 humidity before trusting a high reading.

Ideas to Extend

  • Log readings to Google Sheets or ThingSpeak every 5 minutes for daily graphs.
  • Put the PMS5003 to sleep (SET LOW) between readings to extend the fan life.
  • Switch an air purifier through a relay when AQI goes above 150.
  • Add an SCD40 sensor for true CO2 readings in closed rooms.

1 thought on “ESP32 Air Quality Monitor with PMS5003, BME280, MQ-135, OLED & Web Dashboard”

Leave a Comment