Labs / Electronic modules

GraftSense-MG811 Carbon Dioxide Sensor Module (Open Version)

Author: Li Zisheng · Source: FreakStudio open documentation, v1.4 · License: CC BY 4.0 · Driver code (sensors/mgx_driver): MIT License

Contents
GraftSense-MG811
GraftSense-MG811 U1 U2 R1 LED2 29EE v1.0

I. Module Introduction

MG811 Carbon Dioxide Sensor Module takes the solid electrolyte (NASICON) based MG811 sensor as the core, and realizes concentration sensing by detecting the electromotive force generated by its electrode reaction (which is inversely proportional to the logarithm of CO₂ concentration). In the circuit diagram, the heating electrode of the sensor needs to be matched with a power supply of about 6V; the weak electromotive force output by the signal electrode is amplified in the same direction by the CA3140 high-impedance operational amplifier (with an amplification factor of about 8.5 times) and then outputs an analog signal from the AOUT terminal. Meanwhile, the amplified signal is compared with the reference voltage through the LM393 voltage comparator, and outputs a digital signal from DOUT to realize over-limit trigger. Supported by auxiliary circuits such as filtering and decoupling, power supply and alarm indication, the module has a detection range of 0–10000ppm, integrates both analog quantitative detection and digital qualitative alarm functions, and is widely used in scenarios such as smart home ventilation control, greenhouse monitoring, and industrial fermentation monitoring.

II. Introduction to Main Chips

This module mainly uses MG811 probe, CA3140AMZ96-MS high-impedance operational amplifier and LM393BIDR voltage comparator.

2.1 Chip Overview

MG811 CO2 1 9 20mm 2.3mm

The MG811 carbon dioxide sensor operates based on the principle of solid electrolyte cells, and its electrochemical structure is as follows:

When in a CO₂ atmosphere, the following electrode reaction occurs:

The potential difference (EMF) between the sensor's sensitive electrode and reference electrode conforms to the Nernst equation: EMF = Ec −2 FR × T ln (P (CO2))
, where P (CO2) is the partial pressure of CO₂, Ec is a constant, R is the gas constant, T is the absolute temperature (K), and F is the Faraday constant. It can be seen that the output potential is inversely proportional to the logarithm of the CO₂ partial pressure, which can reflect the change in CO₂ concentration.

In addition, an external circuit is required to supply a heating voltage to the sensor, so that its surface temperature is high enough to form an effective "battery" and output a voltage signal; besides, during measurement, the impedance of the amplifier 100~1000 GΩ shall be within this range, and the test current shall be controlled below 1 pA, so as to ensure the detection accuracy of the weak potential signal and avoid interfering with the electrochemical characteristics of the battery.

2.2 Pin Definition

MG811 1 9

The pins of the MG811 carbon dioxide sensor probe mainly serve two functions: heating power supply and signal output, with the specific definitions as follows:

2.3 Functional Block Diagram

None.

2.4 Performance Parameters

GraftSense-MG811 6.0 0.1V 30.0 5 200mA 1200mW 20 50 2.4
GraftSense-MG811 20 70 30 50mV 350 10000ppmCO2 CO2 2.4
MG811 CO2 28 65 21 O2 350ppm 5s

2.5 Reference Circuit

GraftSense-MG811 6V 0.1V MG811

2.6 Chip Configuration

None.

None.

2.8 PCB Routing Precautions

There are no special requirements, except that this electronic module requires a relatively large current (about 200mA), so pay attention to widening the traces during wiring.

III. Circuit Engineering

3.1 Circuit Source Engineering

To obtain the circuit source project, please follow the official account [Freak Embedded]

3.2 Module Usage Instructions

The schematic diagram of this module is shown below:

SCH_Schematic1_MG811 Carbon Dioxide Sensor Module_v1.1_2025-09-16.pdf 3.1 MB

GraftSense-MG811 U1 U2 U3 U4 R1 R10 C1 C5 LED1
GraftSense-MG811 v1.0

This module provides two types of output interfaces:

As shown in the schematic diagram, the core part of its circuit consists of an operational amplifier circuit and a voltage comparison circuit:

Adjusting R10 (10kΩ) will change the threshold level of the voltage comparison circuit, thereby affecting the "alarm trigger point" of the module for CO₂ concentration. The larger the resistance value, the higher the CO₂ concentration required to trigger the alarm; the smaller the resistance value, the lower the CO₂ concentration that triggers the alarm.

3.3 Application Experiment

Here, we use the GraftPort-RP2040 development board for testing, and connect the MG811 carbon dioxide sensor module to communicate with the main controller via the AIN interface.

Here, we first use the HY2.0-4P cable to connect the module to the GraftPort-RP2040 development board's AIN0 interface:

GraftSense-MG811 GraftPort-RP2040 HY2.0-4P AIN0 R5 LED2

The module connections are shown in the following table:

development board pins

Module Pins

Description

Pin 26

AIN (analog pin)

Sensor analog signal input pin

Pin 19

DIN (Digital Pin)

Digital signal input pin after digital comparison of sensor analog signals

Before burning the code, we first need to adjust the digital output threshold of the MG811 carbon dioxide sensor module:

GraftSense-MG811 GraftPort-RP2040 R5 LED2 MG811

Here, we need to search for the relevant driver packages on uPyPI: https://upypi.net/zh/

106

Enter mgx_driver to search, and the following will be displayed:

1.0.0 2020 2 12

Click to copy the local installation command:

1.0.0 2026 02 12 GraftSense-MG811

Here, we can import the module driver library code via the mip tool. Below are the usage commands for the mpremote tool:

mpremote mip install github:FreakStudioCN/GraftSense-Drivers-MicroPython/sensors/mgx_driver

After importing the MG carbon dioxide sensor module - MicroPython driver code, copy the following main.py code into our project:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time    : 2025/08/20 10:21
# @Author  : 缪贵成
# @File    : main.py
# @Description : Test the MG series gas sensor module driver program

# ======================================== Import Modules =========================================

from machine import Pin, ADC
import time
from time import sleep
from mgx import MGX

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# User callback function
def mg_callback(voltage: float) -> None:
    """
    Called when the comparator pin triggers an interrupt; prints the current voltage value.

    Args:
        voltage (float): Voltage value (unit: V).

    ==========================================

    This function is called when the comparator pin triggers an IRQ,
    and prints the measured voltage.

    Args:
        voltage (float): Voltage value in volts.

    """
    print("[IRQ] Voltage: {:.3f} V".format(voltage))

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("Measuring Gas Concentration with MG Series Gas Sensor Modules")

# Pico ADC0 (GPIO26)
adc = ADC(Pin(26))
# Comparator output (GPIO15, optional)
comp = Pin(19, Pin.IN)
mg = MGX(adc, comp, mg_callback, rl_ohm=10000, vref=3.3)

# Select a built-in polynomial (MG811, MG812)
mg.select_builtin("MG811")

# Pass in a custom polynomial
# mq.set_custom_polynomial([1.0, -2.5, 3.3])

# ========================================  Main Program  ===========================================

print("===== MG Sensor Test Program Started =====")
try:
    while True:
        # Read voltage
        v = mg.read_voltage()
        print("Voltage: {:.3f} V".format(v))

        # Read ppm (5 samples, 200 ms interval)
        ppm = mg.read_ppm(samples=5, delay_ms=200)
        print("Gas concentration: {:.2f} ppm".format(ppm))

        print("-" * 40)
        # Main loop interval
        sleep(2)
except KeyboardInterrupt:
    print("User interrupted, exiting program...")
finally:
    mg.deinit()
    print("Sensor resources released.")

To flash the code, open a terminal and use the mpremote tool to connect to the main controller; the output is as follows:

GraftSense-MG811 1.375V 100.10 1.413V LED2

When no trigger occurs, it will print the pin voltage and gas concentration; when the sensor's trigger state changes, the callback function mg_callback will be invoked. In the example, when the callback function is triggered, the content [IRQ] will be printed, and at the same time LED2 (the sensor trigger indicator) will light up.

It should be noted here that our MG811 carbon dioxide sensor module only supports qualitative gas identification and cannot directly achieve quantitative detection (the coefficients in the code are simulated values rather than real ones).

To achieve quantitative measurement capability, a professional calibration process is required: simulate different temperature and humidity environments by means of a high-low temperature alternating chamber, use standard calibration gas samples corresponding to the target gas, collect the analog voltage signals output by the sensor under various environmental conditions, and finally establish a correlation model of "temperature and humidity - gas concentration - output voltage" through curve fitting to complete the calibration for quantitative detection.

Here, we briefly explain the calibration concept for you. First, professional calibration equipment and consumables need to be prepared, and the core configurations include a high-low temperature alternating test chamber (used to simulate different temperature and humidity environments and eliminate the interference of environmental factors on sensor output), target gas standard samples with multiple gradient concentrations (which need to match the detection range of the sensor, such as combustible gas standard gas with a gradient of 0-1000ppm), and a gas test chamber (whose core function is to provide a sealed and uniform standard gas environment for the sensor probe to ensure the accuracy of calibration data).

Next, on the embedded device side, collect the temperature value, humidity value, voltage output and the gas concentration value of the calibration gas near the probe, and save them to a file (it is required to collect as much data as possible under different temperature, humidity and gas concentration conditions after the probe is powered on in advance and fully preheated):

GraftSense-MG811 A247 C16268 C16291 29.25ppm 5.41

Then, on the PC side, you can use Python to write code for data fitting, which includes:

GraftSense-MG811
GraftSense-MG811
GraftSense-MG811 Carbon Dioxide Sensor Module (Open Version)

IV. Drivers

mgx_driver.zip 11 KB

None.

VI. Revision History

Document Version

Revision Date

Modifier

Revised Content

v1.0

2025.8.31

Xing Gao

Initialize Document

v1.1

2025-09-17

Li Zisheng

Added 2.8 PCB routing precautions

Revised Section 3, Instructions for Circuit Source Project and Module Usage, and added a secondary heading:

3.1 Circuit Source Engineering, 3.2 Module Usage Instructions, 3.3 Application Experiments

The BOM sheet has not been finally checked, the driver has not been re-verified, and the 3.3 application experiment

Not yet specified.

v1.2

2025-12-29

Li Zisheng

Added application experiments and production files

v1.3

2025-12-31

Sin Ruili

Create an open version of the document based on the internal document version v1.2.

v1.4

2026-03-29

Sin Ruili

Modified the application experiment section.

VII. Relevant Materials

7.1 Chip Datasheet

MG811 CO2 Gas Sensor.pdf 128 KB

CA3140AMZ96-MS Datasheet.pdf 974 KB

LM393BIDR Datasheet.pdf 3.4 MB

7.2 Unique Icons for PCB Silk Screen

GraftSense-MG811