/
th02_driver.go
241 lines (200 loc) · 6.22 KB
/
th02_driver.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
* Copyright (c) 2018 Nick Potts <nick@the-potts.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package i2c
// TH02Driver is a driver for the TH02-D based devices.
//
// This module was tested with a Grove "Temperature&Humidity Sensor (High-Accuracy & Mini ) v1.0"
// from https://www.seeedstudio.com/Grove-Temperature-Humidity-Sensor-High-Accuracy-Min-p-1921.htm
// Datasheet is at http://www.hoperf.com/upload/sensor/TH02_V1.1.pdf
import (
"fmt"
"time"
"gobot.io/x/gobot"
)
const (
// TH02Address is the default address of device
TH02Address = 0x40
//TH02ConfigReg is the configuration register
TH02ConfigReg = 0x03
)
//Accuracy constants for the TH02 devices
const (
TH02HighAccuracy = 0 //High Accuracy
TH02LowAccuracy = 1 //Lower Accuracy
)
// TH02Driver is a Driver for a TH02 humidity and temperature sensor
type TH02Driver struct {
Units string
name string
connector Connector
connection Connection
Config
addr byte
accuracy byte
heating bool
delay time.Duration
}
// NewTH02Driver creates a new driver with specified i2c interface.
// Defaults to:
// - Using high accuracy (lower speed) measurements cycles.
// - Emitting values in "C". If you want F, set Units to "F"
// Params:
// conn Connector - the Adaptor to use with this Driver
//
// Optional params:
// i2c.WithBus(int): bus to use with this driver
// i2c.WithAddress(int): address to use with this driver
//
func NewTH02Driver(a Connector, options ...func(Config)) *TH02Driver {
s := &TH02Driver{
Units: "C",
name: gobot.DefaultName("TH02"),
connector: a,
addr: TH02Address,
Config: NewConfig(),
heating: false,
}
s.SetAccuracy(1)
for _, option := range options {
option(s)
}
return s
}
// Name returns the name for this Driver
func (s *TH02Driver) Name() string { return s.name }
// SetName sets the name for this Driver
func (s *TH02Driver) SetName(n string) { s.name = n }
// Connection returns the connection for this Driver
func (s *TH02Driver) Connection() gobot.Connection { return s.connector.(gobot.Connection) }
// Start initializes the TH02
func (s *TH02Driver) Start() (err error) {
bus := s.GetBusOrDefault(s.connector.GetDefaultBus())
address := s.GetAddressOrDefault(int(s.addr))
s.connection, err = s.connector.GetConnection(address, bus)
return err
}
// Halt returns true if devices is halted successfully
func (s *TH02Driver) Halt() (err error) { return }
// SetAddress sets the address of the device
func (s *TH02Driver) SetAddress(address int) { s.addr = byte(address) }
// Accuracy returns the accuracy of the sampling
func (s *TH02Driver) Accuracy() byte { return s.accuracy }
// SetAccuracy sets the accuracy of the sampling. It will only be used on the next
// measurment request. Invalid value will use the default of High
func (s *TH02Driver) SetAccuracy(a byte) {
if a == TH02LowAccuracy {
s.accuracy = a
} else {
s.accuracy = TH02HighAccuracy
}
}
// SerialNumber returns the serial number of the chip
func (s *TH02Driver) SerialNumber() (sn uint32, err error) {
ret, err := s.readRegister(0x11)
return uint32(ret) >> 4, err
}
// Heater returns true if the heater is enabled
func (s *TH02Driver) Heater() (status bool, err error) {
st, err := s.readRegister(0x11)
return (0x02 & st) == 0x02, err
}
func (s *TH02Driver) applysettings(base byte) byte {
if s.accuracy == TH02LowAccuracy {
base = base & 0xd5
} else {
base = base | 0x20
}
if s.heating {
base = base & 0xfd
} else {
base = base | 0x02
}
base = base | 0x01 //set the "sample" bit
return base
}
// Sample returns the temperature in celsius and relative humidity for one sample
func (s *TH02Driver) Sample() (temperature float32, relhumidity float32, _ error) {
if err := s.writeRegister(TH02ConfigReg, s.applysettings(0x10)); err != nil {
return 0, 0, err
}
rawrh, err := s.readData()
if err != nil {
return 0, 0, err
}
relhumidity = float32(rawrh>>4)/16.0 - 24.0
if err := s.writeRegister(TH02ConfigReg, s.applysettings(0x00)); err != nil {
return 0, relhumidity, err
}
rawt, err := s.readData()
if err != nil {
return 0, relhumidity, err
}
temperature = float32(rawt>>2)/32.0 - 50.0
switch s.Units {
case "F":
temperature = 9.0/5.0*temperature + 32.0
}
return temperature, relhumidity, nil
}
//writeRegister writes the value to the register.
func (s *TH02Driver) writeRegister(reg, value byte) error {
_, err := s.connection.Write([]byte{reg, value})
return err
}
//readRegister returns the value of a single regusterm and a non-nil error on problem
func (s *TH02Driver) readRegister(reg byte) (byte, error) {
if _, err := s.connection.Write([]byte{reg}); err != nil {
return 0, err
}
rcvd := make([]byte, 1)
_, err := s.connection.Read(rcvd)
return rcvd[0], err
}
/*waitForReady blocks for up to the passed duration (which defaults to 50mS if nil)
until the ~RDY bit is cleared, meanign a sample has been fully sampled and is ready for reading.
This is greedy.
*/
func (s *TH02Driver) waitForReady(dur *time.Duration) error {
wait := 100 * time.Millisecond
if dur != nil {
wait = *dur
}
start := time.Now()
for {
if time.Since(start) > wait {
return fmt.Errorf("timeout on \\RDY")
}
//yes, i am eating the error.
if reg, _ := s.readRegister(0x00); reg == 0 {
return nil
}
}
}
/*readData fetches the data from the data 'registers'*/
func (s *TH02Driver) readData() (uint16, error) {
if err := s.waitForReady(nil); err != nil {
return 0, err
}
if n, err := s.connection.Write([]byte{0x01}); err != nil || n != 1 {
return 0, fmt.Errorf("n=%d not 1, or err = %v", n, err)
}
rcvd := make([]byte, 3)
n, err := s.connection.Read(rcvd)
if err != nil || n != 3 {
return 0, fmt.Errorf("n=%d not 3, or err = %v", n, err)
}
return uint16(rcvd[1])<<8 + uint16(rcvd[2]), nil
}