-
Notifications
You must be signed in to change notification settings - Fork 1
/
mhz19b.go
81 lines (65 loc) · 1.47 KB
/
mhz19b.go
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
package mhz19b
import (
"errors"
"time"
"github.com/tarm/serial"
)
type MHZ19B struct {
SerialConfig *serial.Config
}
func New(device string) *MHZ19B {
serialConfig := &serial.Config{Name: device, Baud: 9600, Size: 8, Parity: 0, StopBits: 1}
mhz19b := &MHZ19B{SerialConfig: serialConfig}
return mhz19b
}
func (mhz19b *MHZ19B) CalibrateDefault() error {
port, err := serial.OpenPort(mhz19b.SerialConfig)
if err != nil {
return err
}
defer port.Close()
// Reset default point (400ppm)
_, err = port.Write([]byte{0xFF, 0x01, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78})
if err != nil {
return err
}
time.Sleep(time.Second)
return nil
}
func (mhz19b *MHZ19B) Read() (int, error) {
port, err := serial.OpenPort(mhz19b.SerialConfig)
if err != nil {
return 0, err
}
defer port.Close()
// Request CO2 concentration
_, err = port.Write([]byte{0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79})
if err != nil {
return 0, err
}
time.Sleep(time.Second)
// Response CO2 concentration
buf := make([]byte, 9)
_, err = port.Read(buf)
if err != nil {
return 0, err
}
crc := getCheckSum(buf)
if buf[8] != crc {
return 0, errors.New("CRC error")
}
return int(buf[2])*256 + int(buf[3]), nil
}
func Read(device string) (ppm int, err error) {
mhz19b := New(device)
return mhz19b.Read()
}
func getCheckSum(packet []byte) byte {
var checksum byte = 0
for i := 1; i < 8; i++ {
checksum += packet[i]
}
checksum = 255 - checksum
checksum += 1
return checksum
}