SG111A CO2 Sensor and Python

You are here:
< Back

The SG111A CO2 sensor is a low cost NDIR CO2 sensor which can be easily integrated into your product development or maker project.

We’ve written an Arduino hookup guide and started a GitHub repository with Arduino compatible code:¬†https://github.com/AretasSensorNetworks/SG111A

However, testing and debugging the sensor output is just as easy in Python with a low-cost FTDI converter from Sparkfun or Adafruit.

Connect the devices as shown:

FTDI Adapter +5V -> SG111A +5V

FTDI Adapter GND -> SG111A GND

FTDI Adapter TX -> SG111A RX

FTDI Adapter RX -> SG111A TX

Once you have connected everything correctly and have plugged the FTDI adapter into your PC, a COM port will appear in the Device Manager.

This article assumes you have a running installation of Python on your PC. If not, download it and install it from the Python web site.

If you do not have the serial module installed, install it with the following command:

python -m pip install pyserial

Next, you can create a script with the following Python code and run it to view the data from the sensor. Make sure you change the “ser.port” line to match the COM Port listed in the device manager.

import serial
import time

ser = serial.Serial()
ser.port = "COM10"
ser.baudrate = 9600
ser.parity = serial.PARITY_NONE
ser.bytesize = serial.EIGHTBITS
ser.stopbits = 1
ser.open()


def printpacket(data: bytearray, msg):
    print(msg)
    for bb in data:
        print(hex(bb))


try:
    while True:

        packet = bytearray()
        packet.append(0xAA)
        packet.append(0x55)
        packet.append(0x14)

        ser.write(packet)

        time.sleep(1)

        buffer = ser.read(8)

        for b in buffer:
            print(hex(b))

        print(buffer)

        ppm = (buffer[5] * 256) + buffer[4]

        print("ppm: " + str(ppm))

        time.sleep(10)

except KeyboardInterrupt:
    exit()

If you don’t have a Python IDE, you can use notepad and just save the file as sg111a-basic.py

Then, to run the script, just type

python sg111a-basic.py

That’s it! Leave any questions or comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.