CO2 monitor

MH-Z19B CO2 meter with an OLED and a ventilation alert, handy for bedrooms and offices.

Climate & heating Board: ESP32 DevKit V1 (WROOM-32) Level: ●●○ ⏱ 1–2 h

🛒 Ready kit in the shop

Bedrooms get stuffy before you notice it

The MH-Z19B is a real NDIR sensor, not a gas "guess", and that makes it one of the most useful sensors for an apartment. As a rough guide, under 800 ppm is fresh, over 1000 ppm means open a window, and around 1400 ppm is a room that has been closed for hours.

What to know before you wire it

The sensor needs 5 V because its lamp draws a few hundred milliamps in bursts, but its UART works at 3.3 V logic. After switching on it needs about three minutes to warm up. The factory auto-calibration assumes that once a day the room falls to about 400 ppm. In a bedroom that is occupied all day and night, it never does, and the readings slowly drift low. Disable ABC in that case and calibrate by hand outdoors.

  • Place it away from your breath and not directly next to a window.
  • Use two thresholds, a soft reminder and a loud one, so it does not nag.
  • Add a sleep schedule that turns the buzzer off at night.

Components

  • ESP32 DevKit V1 (30 pin, WROOM-32)
  • MH-Z19B CO2 sensor (NDIR)
  • OLED 0.96" 128x64 I2C SSD1306
  • Dupont jumper wires (M-F, M-M)

Wiring

Module Module pin ESP32 pin Note
MH-Z19B Vin / GND 5V / GND needs 5 V and ~150 mA peaks
MH-Z19B TX UART GPIO16 (RX2) 3.3 V logic, OK
MH-Z19B RX UART GPIO17 (TX2)

Code

#include <WiFi.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";

bool connectWiFi(uint32_t timeoutMs = 20000) {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  uint32_t t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < timeoutMs) {
    delay(250);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("IP: ");
    Serial.println(WiFi.localIP());
    return true;
  }
  return false;
}
#include <WebServer.h>

WebServer server(80);
String buildJson();   // implemented in the project below

String num(float v, int d = 1) { return isnan(v) ? String("null") : String(v, d); }

const char PAGE_HTML[] PROGMEM = R"rawliteral(
<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32</title>
<style>body{font-family:system-ui;background:#0b0f14;color:#e6edf3;margin:20px}table{border-collapse:collapse}td{padding:6px 14px;border-bottom:1px solid #223}button,input{font-size:16px;padding:8px 14px;margin:4px;border-radius:6px;border:1px solid #345;background:#16202b;color:#e6edf3}</style>
</head><body><h2>ESP32</h2><table id="t"></table>
<script>
function load(){fetch('/json').then(r=>r.json()).then(d=>{let h='';for(const k in d){h+='<tr><td>'+k+'</td><td>'+d[k]+'</td></tr>';}document.getElementById('t').innerHTML=h;});}
load();setInterval(load,2000);
</script></body></html>
)rawliteral";

void startWeb() {
  server.on("/", []() { server.send_P(200, "text/html", PAGE_HTML); });
  server.on("/json", []() { server.send(200, "application/json", buildJson()); });
  server.begin();
}
// MH-Z19B read command over UART2 (no extra library)
int co2 = -1;
int readCO2() {
  const uint8_t cmd[9] = {0xFF, 0x01, 0x86, 0, 0, 0, 0, 0, 0x79};
  while (Serial2.available()) Serial2.read();
  Serial2.write(cmd, 9);
  uint8_t r[9]; uint32_t t0 = millis(); int n = 0;
  while (n < 9 && millis() - t0 < 500) if (Serial2.available()) r[n++] = Serial2.read();
  if (n < 9 || r[0] != 0xFF || r[1] != 0x86) return -1;
  uint8_t s = 0; for (int i = 1; i < 8; i++) s += r[i]; s = 0xFF - s + 1;
  if (s != r[8]) return -1;
  return r[2] * 256 + r[3];
}
String buildJson() { return String("{"co2_ppm":") + co2 + ","air":"" + (co2 < 0 ? "?" : co2 < 800 ? "good" : co2 < 1200 ? "ventilate" : "bad") + ""}"; }
void setup() {
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, 16, 17);
  connectWiFi();
  startWeb();
}
void loop() {
  server.handleClient();
  static uint32_t t = 0;
  if (millis() - t > 5000) { t = millis(); co2 = readCO2(); Serial.println(co2); }
}

Build tips

  • Let the sensor warm up 3 minutes before trusting values.
  • Disable ABC if the room is always occupied; or ventilate outdoors air weekly for calibration.

What you need

Buy the parts kit · Estimated total: $28.00

ESP32 DevKit V1 (30 pin, WROOM-32) × 1
$4.00
Buy at AliExpress Buy at Amazon.com
MH-Z19B CO2 sensor (NDIR) × 1
$20.00
Buy at AliExpress Buy at Amazon.com
OLED 0.96" 128x64 I2C SSD1306 × 1
$2.50
Buy at AliExpress Buy at Amazon.com
Dupont jumper wires (M-F, M-M) × 1
$1.50
Buy at AliExpress Buy at Amazon.com
🇺🇦 Ukraine🌍 Other countries

Ukraine: we buy and sell these parts ourselves, order them on this site.

Some links are affiliate links: we may earn a commission at no extra cost to you.

Related ideas

Temperature & humidity station

BME280 plus an OLED screen: temperature, humidity and pressure on the display, a web page and Home Assistant.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●○○ Beginner
  • Build time 1 h
Pick parts / kit

Dust PM2.5 air monitor

PMS5003 particle sensor plus BME280: PM1 / PM2.5 / PM10, temperature and humidity on a web page.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●●○ Intermediate
  • Build time 1–2 h
Pick parts / kit

Network cabinet temperature watch

Two probes at the top and the bottom of a closet with the router, switch and NAS, and an alarm before the equipment overheats in summer.

  • Board ESP32 DevKit V1 (WROOM-32)
  • Level ●○○ Beginner
  • Build time 1–2 h
Pick parts / kit

← All module ideas →

Comments

No comments yet. Share your experience or ask a question.

Comments are moderated.