Co2 sensor not working




I´m just trying to get the Co2 MH-Z16 up and running. I´m using a raspberry pi 3 b+ wit a grove pi+. So far i disabeld serial communication, diabeld the blothoth on s0 and the Sensor is connected to the priser port of the grove pi+. When im using the python Co2 test script ( i get the following output:

_Traceback (most recent call last):_
_  File "/ directory/", line 7, in <module>_
_    [ppm,temp]=
_  File "/directory/", line 24, in read_
_    ser.write(self.cmd_get_sensor)_
_  File "/directory/", line 518, in write_
_    d = to_bytes(data)_
_  File "/directory/", line 63, in to_bytes_
_    raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))_
_TypeError: unicode strings are not supported, please encode to bytes: 'ÿ\x01\x86\x00\x00\x00\x00\x00y'_

thats the problem so far…


hi again,

i came a little bit fürther… by changing the codeline in the python libary at line 13 to:
cmd_get_sensor = b"\xff\x01\x86\x00\x00\x00\x00\x00\x79"
the bytes seem to be send but i get the following error message:

Traceback (most recent call last):
  File "/home/pi/netzspeicher/Generic-FlashDisk-01/", line 7, in <module>
  File "/home/pi/netzspeicher/Generic-FlashDisk-01/", line 26, in read
    high_level = struct.unpack('B', self.inp[2])[0]
TypeError: a bytes-like object is required, not 'int'

so it sends data back but not in bytes but in integers, so may anyone can help me with that so i can recive bytes instead of integers?
any help is welcomed


Hi @hugo112,

I think it may be using Python 3. Can you tell us which version are you using? If it’s Python 3, can you give it a shot with Python 2 instead?

Thank you!



thanks for ur reply, but i got it working in the meantime.


Hi @hugo112,

That’s great. What was that did it for you?




i just worked through the errors i got till it worked… im new to programing so im a little astonished myself. I can post the code if u like me to.


Hi @hugo112,

Yeah sure, why not. Thanks a lot! :slight_smile:



sure no problem, here is th new grove_co2_lib:

import serial
# import time

ser = serial.Serial(’/dev/ttyAMA0’, 9600, timeout = 1)

class CO2:

inp = []
cmd_calibrate_sensor = b"\xff\x87\x87\x00\x00\x00\x00\x00\xf2"
cmd_get_sensor = b"\xff\x01\x86\x00\x00\x00\x00\x00\x79"

def init(self):

def calibration(self):
cal = “calibration Done”

def read(self):
self.inp =
high_level = self.inp[2]
low_level = self.inp[3]
temp_co2 = self.inp[4] - 46
conc = high_level * 256 + low_level
return [conc, temp_co2]

except IOError:
return [-1, -1]

# if name == “main”:
# while True:
# print(
# time.sleep(1)


oh, i didnt post the tabs, sorry