Building an IoT Indoor Air Quality Monitor with MicroPython, ESP32, and the SGP30 Sensor

Main Facts: A Smart Solution to Indoor Pollution
In an era where modern architecture prioritizes energy efficiency by sealing buildings tighter than ever, the air we breathe indoors has quietly transformed into a hidden health hazard. Whether in crowded school classrooms, bustling corporate offices, or our own living rooms, poorly ventilated spaces accumulate high concentrations of carbon dioxide ($textCO_2$) and Total Volatile Organic Compounds (TVOCs). These invisible pollutants cause drowsiness, headaches, cognitive fatigue, and—crucially—serve as primary vectors for airborne pathogens like the viruses responsible for COVID-19.
To combat this, DIY electronics and IoT enthusiasts now have access to a straightforward, highly effective remedy: a compact, intelligent air quality monitoring device. Built around the Heltec WiFi Kit 32 microcontroller board and the Sensirion SGP30 gas sensor, this open-source project continuously measures $textCO_2$ and TVOC levels. It displays real-time metrics on an integrated OLED screen and issues immediate visual warnings via high-visibility LEDs when room ventilation is urgently required.

Powered by MicroPython and programmed via the Thonny IDE, this project bridges the gap between hardware tinkering and practical, real-world utility, offering an affordable blueprint for healthier indoor environments.
Chronology: From Concept to a Fully Functional Prototype
Developing an embedded IoT project requires a logical, step-by-step approach—from selecting components to writing the control software and validating hardware behavior on a breadboard.

Phase 1: Hardware Selection and Design
The development cycle began by identifying core system requirements: a processing unit capable of running a modern lightweight interpreter, a reliable multi-gas sensor, a local display, and flexible general-purpose input/output (GPIO) pins. The Heltec WiFi Kit 32 was chosen as the central processing unit due to its onboard ESP32 chip and 0.96-inch OLED screen. The Sensirion SGP30 breakout board was selected for gas sensing due to its robust architecture for detecting $textCO_2$ equivalents and TVOC particles.
Phase 2: Physical Wiring and Prototyping
Interfacing the components required minimal hardware overhead. Using standard male-female jumper wires and a prototyping breadboard, the SGP30 sensor was connected via an $textI^2textC$ bus, utilizing four lines: clock ($textSCL$), data ($textSDA$), ground ($textGND$), and a $3.3textV$ positive power supply. Two indicator LEDs (red and green) were linked to dedicated ESP32 GPIO pins, each protected by a calculated $220text-ohm$ current-limiting resistor to prevent hardware overloading.

Phase 3: Software Environment and Interpreter Flashing
Because the Heltec board does not ship with MicroPython pre-installed, the flashing process required obtaining the official v1.19 binary from the MicroPython repository. Using Espressif’s free esptool utility via a Windows console, the ESP32’s flash memory was completely erased before writing the MicroPython interpreter to address 0x1000.
Phase 4: Driver Integration and Coding
With the interpreter active, the Thonny IDE was configured to interface directly with the ESP32 port. Essential driver libraries—specifically Adafruit’s SSD1306 OLED driver and the alexmrqt SGP30 driver—were uploaded to the device’s internal file system alongside the main application logic (air_quality.py). Custom configuration text files (co2eq_th.txt and hist_th.txt) were created to manage user-defined thresholds and hysteresis parameters locally.

Supporting Data: Hardware Specifications and Technical Architecture
Understanding the underlying technical specifications ensures the device performs reliably over long operational periods. The architecture relies on robust components designed for edge-computing applications.
Heltec WiFi Kit 32 Microcontroller
Serving as the brain of the operation, the Heltec module packs immense capability into a tiny footprint:

- Microcontroller: Tensilica Xtensa Dual-Core 32-bit LX6, operating at 240 MHz.
- Memory: 520 KB of on-board SRAM and 32 MB of external Flash memory, providing a generous buffer for application software and logging frameworks.
- Display: Integrated 0.96-inch monochrome OLED display (driven via $textI^2textC$ on pins GPIO 4 and GPIO 15).
- Connectivity: Standard 802.11 b/g/n Wi-Fi transceiver and Bluetooth v4.2 BR/EDR/BLE.
- Power Management: Integrated LiPo battery charging circuit, allowing for uninterrupted operation via a single-cell battery when disconnected from mains power.
Sensirion SGP30 Air Quality Sensor
The SGP30 is an oxide-based gas sensor designed for indoor air quality monitoring. Key parameters include:
- Metrics Tracked: $textCO_2$ equivalent ($textCO_2texteq$) measured in parts per million (ppm) and Total Volatile Organic Compounds (TVOC) measured in parts per billion (ppb).
- Interface: Standard $textI^2textC$ communication protocol (requiring $textSCL$ on GPIO 18 and $textSDA$ on GPIO 19).
- Self-Calibration: Internal dynamic baseline compensation algorithms that automatically calibrate sensor drift over time to maintain long-term accuracy.
Hardware Wiring Reference
The physical interconnections between the components are systematically mapped out as follows:

| Component A | Pin / Function | Component B | Pin / Function | Notes |
|---|---|---|---|---|
| SGP30 Board | $textVCC$ | Heltec WiFi Kit 32 | $3.3textV$ | Positive Power Supply |
| SGP30 Board | $textGND$ | Heltec WiFi Kit 32 | $textGND$ | Common Ground |
| SGP30 Board | $textSCL$ | Heltec WiFi Kit 32 | GPIO 18 | $textI^2textC$ Clock Line |
| SGP30 Board | $textSDA$ | Heltec WiFi Kit 32 | GPIO 19 | $textI^2textC$ Data Line |
| Green LED | Anode (+) | Heltec WiFi Kit 32 | GPIO 2 | Via $220 Omega$ Resistor |
| Red LED | Anode (+) | Heltec WiFi Kit 32 | GPIO 17 | Via $220 Omega$ Resistor |
Official Responses and Engineering Best Practices
When designing embedded environmental monitors, adhering to manufacturer guidelines is vital to prevent erratic sensor behavior. According to Sensirion’s technical documentation for the SGP30, baseline stability dictates measurement accuracy.
The control software addresses this requirement through a strict initialization and calibration sequence:

- Warm-Up Delay: Upon booting, the system pauses for a mandatory 15-second initialization window (
SENS_INIT_DELAY_S) to let the internal heating elements reach operational temperature. - Baseline Updates: To counteract sensor drift, the software automatically saves and updates sensor baseline calibration data. Following manufacturer specs, the baseline is updated after the first 12 hours of continuous operation, and subsequently once every hour.
- Hysteresis Implementation: To prevent rapid flickering of the indicator LEDs when $textCO_2$ concentrations hover precisely around the threshold limit, the system introduces a programmable hysteresis value (defaulting to $10text ppm$). The green LED remains lit until concentrations exceed the upper threshold (
co2eq_th), while the red warning light stays active until levels drop below the threshold minus the hysteresis value (co2eq_th - hysteresis).
Implications: Energy Efficiency, Public Health, and Future IoT Horizons
The deployment of low-cost, open-source air quality monitors carries profound implications for modern building management, public health, and smart-home integration.
Mitigating Health Risks in Confined Spaces
In schools and offices, stagnant air directly correlates with diminished cognitive performance, increased fatigue, and accelerated transmission of respiratory pathogens. By offering an unambiguous, binary visual indicator—green for safe, red for stagnant—occupants no longer have to guess when a room requires fresh air. Opening windows strategically based on hard data rather than guesswork significantly lowers pathogen loads without unnecessarily chilling or overheating indoor spaces.

Balancing Energy Conservation and Indoor Climate Control
A major dilemma in modern architecture is the trade-off between thermal efficiency and indoor air quality. Keeping windows shut minimizes energy consumption for heating and cooling systems, but traps harmful pollutants. This monitoring device acts as an optimization bridge: it ensures windows are only opened when strictly necessary, thereby minimizing thermal losses and reducing overall energy waste.
Future IoT Scalability
Because the Heltec WiFi Kit 32 features a robust ESP32 microcontroller with built-in Wi-Fi and Bluetooth capabilities, this standalone prototype is easily expandable. Future iterations of the firmware can leverage the Wi-Fi stack to publish real-time $textCO_2$ and TVOC metrics directly to a web dashboard, integrate with home automation systems via MQTT, or dispatch automated security alerts and ventilation reminders directly to smartphones via Telegram bots or email services.

By combining accessible components, modern scripting languages like MicroPython, and sound engineering principles, this project empowers developers, educators, and citizens to take active control of the air they breathe.
