-
Notifications
You must be signed in to change notification settings - Fork 0
/
mhz14a.py
49 lines (36 loc) · 1.12 KB
/
mhz14a.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python3
# Ref. https://github.com/chez-shanpu/co2-sensor-pi/blob/master/sensor.py
import serial
import time
import json
class MHZ14A():
PACKET = [0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]
ZERO = [0xff, 0x01, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78]
def __init__(self, ser):
self.serial = serial.Serial(ser, 9600, timeout=1)
time.sleep(2)
def zero(self):
self.serial.write(bytearray(MHZ14A.ZERO))
def get(self):
self.serial.write(bytearray(MHZ14A.PACKET))
res = self.serial.read(size=9)
res = bytearray(res)
checksum = 0xff & (~(res[1] + res[2] + res[3] + res[4] + res[5] + res[6] + res[7]) + 1)
if res[8] == checksum:
return (res[2] << 8) | res[3]
else:
raise Exception("checksum: " + hex(checksum))
def close(self):
self.serial.close()
def main():
co2 = MHZ14A("/dev/ttyS1")
try:
print(json.dumps(co2.get()))
except:
print("Err")
pass
co2.close()
if __name__ == '__main__':
# co2 = MHZ14A("/dev/ttyS1")
# co2.zero()
main()