-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmhz19.py
More file actions
95 lines (77 loc) · 2.45 KB
/
mhz19.py
File metadata and controls
95 lines (77 loc) · 2.45 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
MH-Z19 CO2 Sensor from Winsen
MH-Z19B + MH-Z19C driver for MicroPython
Author: Florian "overflo" Bittner - 12/2020
Find me here: https://overflo.info / https://twitter.com/overflo / https://github.com/overflo23
Version 0.1
License MIT
Some hints taken from:
https://github.com/nara256/mhz19_uart/blob/master/src/MHZ19_uart.cpp
This implements a simple class to get data from the MH-Z19 Sesors
It will tell you
- PPM
- Room temperature (not very accurate) - not documented in Module Datasheet
- CO2 Status (whatever that is) - Neither documented in Module Datasheet
"""
from machine import UART
import time
import sys
class mhz19:
def __init__(self, uart_no):
self.uart_no = uart_no
self.start()
self.ppm = 0
self.temp = 0
self.co2status = 0
def start(self):
self.uart = UART(self.uart_no, 9600)
self.uart.init(9600, bits=8, parity=None, stop=1, timeout=10)
def stop(self):
while self.uart.any():
self.uart.read(1)
self.uart.deinit()
def get_data(self):
self.uart.write(b"\xff\x01\x86\x00\x00\x00\x00\x00\x79")
time.sleep(0.1)
s = self.uart.read(9)
try:
z = bytearray(s)
except:
return 0
# Calculate crc
crc = self.crc8(s)
if crc != z[8]:
# we should restart the uart comm here..
self.stop()
time.sleep(1)
self.start()
print('CRC error calculated %d bytes= %d:%d:%d:%d:%d:%d:%d:%d crc= %dn' % (
crc, z[0], z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8]))
return 0
else:
self.ppm = ord(chr(s[2])) * 256 + ord(chr(s[3]))
self.temp = ord(chr(s[4])) - 40
self.co2status = ord(chr(s[5]))
return 1
def set_auto_calibrate_zero(self, enable):
if enable:
msg = b'\xff\x01\x79\xa0\x00\x00\x00\x00\xe6'
else:
msg = b'\xff\x01\x79\x00\x00\x00\x00\x00\x86'
self.uart.write(msg)
def calibrate_zero(self):
msg = b'\xff\x01\x87\x00\x00\x00\x00\x00\x78'
self.uart.write(msg)
def crc8(self, a):
crc = 0x00
count = 1
b = bytearray(a)
while count < 8:
crc += b[count]
count = count+1
# Truncate to 8 bit
crc %= 256
# Invert number with xor
crc = ~crc & 0xFF
crc += 1
return crc