We will make use of the pySerial library (https://pyserial.readthedocs.io/en/latest/shortintro.html#opening-serial-ports) for interfacing the carbon dioxide sensor:
- As per the sensor's documentation, the sensor output can be read by initiating the serial port at a baud rateĀ of 9600, no parity, 8 bits, and 1 stop bit. The GPIO serial port is ttyAMA0. The first step in interfacing with the sensor is initiating serial port communication:
import serial
ser = serial.Serial("/dev/ttyAMA0")
- As per the sensor documentation (http://co2meters.com/Documentation/Other/SenseAirCommGuide.zip), the sensor responds to the following command for the carbon dioxide concentration:
Command to read carbon dioxide concentration from the sensor-borrowed from the sensor datasheet
- The command can be transmitted to the sensor as follows:
ser.write(bytearray([0xFE, 0x44, 0x00, 0x08, 0x02, 0x9F, 0x25]))
- The sensor responds with a 7-byte response, which can be read as follows:
resp = ser.read(7)
- The sensor's response is in the following format:
Carbon dioxide sensor response
- According to the datasheet, the sensor data size is 2 bytes. Each byte can be used to store a value of 0 and 255. Two bytes can be used to store values up to 65,535 (255 * 255). The carbon dioxide concentration could be calculated from the message as follows:
high = resp[3]
low = resp[4]
co2 = (high*256) + low
- Put it all together:
import serial
import time
import array
ser = serial.Serial("/dev/ttyAMA0")
print("Serial Connected!")
ser.flushInput()
time.sleep(1)
while True:
ser.write(bytearray([0xFE, 0x44, 0x00, 0x08,
0x02, 0x9F, 0x25]))
# wait for sensor to respond
time.sleep(.01)
resp = ser.read(7)
high = resp[3]
low = resp[4]
co2 = (high*256) + low
print()
print()
print("Co2 = " + str(co2))
time.sleep(1)
- Save the code to a file and try executing it.