forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ads1x15_driver.go
380 lines (316 loc) · 9.31 KB
/
ads1x15_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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package i2c
import (
"errors"
"math"
"strconv"
"time"
"fmt"
"gobot.io/x/gobot"
)
const (
// ADS1x15DefaultAddress is the default I2C address for the ADS1x15 components
ADS1x15DefaultAddress = 0x48
ads1x15PointerConversion = 0x00
ads1x15PointerConfig = 0x01
ads1x15PointerLowThreshold = 0x02
ads1x15PointerHighThreshold = 0x03
// Write: Set to start a single-conversion
ads1x15ConfigOsSingle = 0x8000
ads1x15ConfigMuxOffset = 12
ads1x15ConfigModeContinuous = 0x0000
//Single shoot mode
ads1x15ConfigModeSingle = 0x0100
ads1x15ConfigCompWindow = 0x0010
ads1x15ConfigCompAactiveHigh = 0x0008
ads1x15ConfigCompLatching = 0x0004
ads1x15ConfigCompQueDisable = 0x0003
)
// ADS1x15Driver is the Gobot driver for the ADS1015/ADS1115 ADC
type ADS1x15Driver struct {
name string
connector Connector
connection Connection
gainConfig map[int]uint16
dataRates map[int]uint16
gainVoltage map[int]float64
converter func([]byte) float64
DefaultGain int
DefaultDataRate int
Config
}
// NewADS1015Driver creates a new driver for the ADS1015 (12-bit ADC)
// Largely inspired by: https://github.com/adafruit/Adafruit_Python_ADS1x15
func NewADS1015Driver(a Connector, options ...func(Config)) *ADS1x15Driver {
l := newADS1x15Driver(a, options...)
l.dataRates = map[int]uint16{
128: 0x0000,
250: 0x0020,
490: 0x0040,
920: 0x0060,
1600: 0x0080,
2400: 0x00A0,
3300: 0x00C0,
}
if l.DefaultDataRate == 0 {
l.DefaultDataRate = 1600
}
l.converter = func(data []byte) (value float64) {
result := (int(data[0]) << 8) | int(data[1])
if result&0x8000 != 0 {
result -= 1 << 16
}
return float64(result) / float64(1<<15)
}
return l
}
// NewADS1115Driver creates a new driver for the ADS1115 (16-bit ADC)
func NewADS1115Driver(a Connector, options ...func(Config)) *ADS1x15Driver {
l := newADS1x15Driver(a, options...)
l.dataRates = map[int]uint16{
8: 0x0000,
16: 0x0020,
32: 0x0040,
64: 0x0060,
128: 0x0080,
250: 0x00A0,
475: 0x00C0,
860: 0x00E0,
}
if l.DefaultDataRate == 0 {
l.DefaultDataRate = 128
}
l.converter = func(data []byte) (value float64) {
result := (int(data[0]) << 8) | int(data[1])
if result&0x8000 != 0 {
result -= 1 << 16
}
return float64(result) / float64(1<<15)
}
return l
}
func newADS1x15Driver(a Connector, options ...func(Config)) *ADS1x15Driver {
l := &ADS1x15Driver{
name: gobot.DefaultName("ADS1x15"),
connector: a,
// Mapping of gain values to config register values.
gainConfig: map[int]uint16{
2 / 3: 0x0000,
1: 0x0200,
2: 0x0400,
4: 0x0600,
8: 0x0800,
16: 0x0A00,
},
gainVoltage: map[int]float64{
2 / 3: 6.144,
1: 4.096,
2: 2.048,
4: 1.024,
8: 0.512,
16: 0.256,
},
DefaultGain: 1,
Config: NewConfig(),
}
for _, option := range options {
option(l)
}
// TODO: add commands to API
return l
}
// Start initializes the sensor
func (d *ADS1x15Driver) Start() (err error) {
bus := d.GetBusOrDefault(d.connector.GetDefaultBus())
address := d.GetAddressOrDefault(ADS1x15DefaultAddress)
if d.connection, err = d.connector.GetConnection(address, bus); err != nil {
return err
}
return
}
// Name returns the Name for the Driver
func (d *ADS1x15Driver) Name() string { return d.name }
// SetName sets the Name for the Driver
func (d *ADS1x15Driver) SetName(n string) { d.name = n }
// Connection returns the connection for the Driver
func (d *ADS1x15Driver) Connection() gobot.Connection { return d.connector.(gobot.Connection) }
// Halt returns true if devices is halted successfully
func (d *ADS1x15Driver) Halt() (err error) { return }
// WithADS1x15Gain option sets the ADS1x15Driver gain option.
// Valid gain settings are any of the ADS1x15RegConfigPga* values
func WithADS1x15Gain(val int) func(Config) {
return func(c Config) {
d, ok := c.(*ADS1x15Driver)
if ok {
d.DefaultGain = val
} else {
// TODO: return error for trying to set Gain for non-ADS1015Driver
return
}
}
}
// WithADS1x15DataRate option sets the ADS1x15Driver data rate option.
// Valid gain settings are any of the ADS1x15RegConfigPga* values
func WithADS1x15DataRate(val int) func(Config) {
return func(c Config) {
d, ok := c.(*ADS1x15Driver)
if ok {
d.DefaultDataRate = val
} else {
// TODO: return error for trying to set data rate for non-ADS1015Driver
return
}
}
}
// BestGainForVoltage returns the gain the most adapted to read up to the specified difference of potential.
func (d *ADS1x15Driver) BestGainForVoltage(voltage float64) (bestGain int, err error) {
var max float64
difference := math.MaxFloat64
currentBestGain := -1
for key, value := range d.gainVoltage {
max = math.Max(max, value)
newDiff := value - voltage
if newDiff >= 0 && newDiff < difference {
difference = newDiff
currentBestGain = key
}
}
if currentBestGain < 0 {
err = fmt.Errorf("The maximum voltage which can be read is %f", max)
return
}
bestGain = currentBestGain
return
}
// ReadDifferenceWithDefaults reads the difference in V between 2 inputs. It uses the default gain and data rate
// diff can be:
// * 0: Channel 0 - channel 1
// * 1: Channel 0 - channel 3
// * 2: Channel 1 - channel 3
// * 3: Channel 2 - channel 3
func (d *ADS1x15Driver) ReadDifferenceWithDefaults(diff int) (value float64, err error) {
return d.ReadDifference(diff, d.DefaultGain, d.DefaultDataRate)
}
// ReadDifference reads the difference in V between 2 inputs.
// diff can be:
// * 0: Channel 0 - channel 1
// * 1: Channel 0 - channel 3
// * 2: Channel 1 - channel 3
// * 3: Channel 2 - channel 3
func (d *ADS1x15Driver) ReadDifference(diff int, gain int, dataRate int) (value float64, err error) {
if err = d.checkChannel(diff); err != nil {
return
}
return d.rawRead(diff, gain, dataRate)
}
// ReadWithDefaults reads the voltage at the specified channel (between 0 and 3).
// Default values are used for the gain and data rate. The result is in V.
func (d *ADS1x15Driver) ReadWithDefaults(channel int) (value float64, err error) {
return d.Read(channel, d.DefaultGain, d.DefaultDataRate)
}
// Read reads the voltage at the specified channel (between 0 and 3). The result is in V.
func (d *ADS1x15Driver) Read(channel int, gain int, dataRate int) (value float64, err error) {
if err = d.checkChannel(channel); err != nil {
return
}
mux := channel + 0x04
return d.rawRead(mux, gain, dataRate)
}
// AnalogRead returns value from analog reading of specified pin
func (d *ADS1x15Driver) AnalogRead(pin string) (value int, err error) {
var useDifference = false
var channel int
var read float64
// First case: the ADC is used in difference mode
switch pin {
case "0-1":
useDifference = true
channel = 0
break
case "0-3":
useDifference = true
channel = 1
break
case "1-3":
useDifference = true
channel = 2
break
case "2-3":
useDifference = true
channel = 3
break
}
if useDifference {
read, err = d.ReadDifferenceWithDefaults(channel)
} else {
// Second case: read the voltage at a specific pin, compared to the ground
channel, err = strconv.Atoi(pin)
if err != nil {
return
}
read, err = d.ReadWithDefaults(channel)
}
if err == nil {
value = int(gobot.ToScale(gobot.FromScale(read, 0, d.gainVoltage[d.DefaultGain]), 0, 1023))
}
return
}
func (d *ADS1x15Driver) rawRead(mux int, gain int, dataRate int) (value float64, err error) {
var config uint16
config = ads1x15ConfigOsSingle // Go out of power-down mode for conversion.
// Specify mux value.
config |= uint16((mux & 0x07) << ads1x15ConfigMuxOffset)
// Validate the passed in gain and then set it in the config.
gainConf, ok := d.gainConfig[gain]
if !ok {
err = errors.New("Gain must be one of: 2/3, 1, 2, 4, 8, 16")
return
}
config |= gainConf
// Set the mode (continuous or single shot).
config |= ads1x15ConfigModeSingle
// Get the default data rate if none is specified (default differs between
// ADS1015 and ADS1115).
dataRateConf, ok := d.dataRates[dataRate]
if !ok {
keys := []int{}
for k := range d.dataRates {
keys = append(keys, k)
}
err = fmt.Errorf("Invalid data rate. Accepted values: %d", keys)
return
}
// Set the data rate (this is controlled by the subclass as it differs
// between ADS1015 and ADS1115).
config |= dataRateConf
config |= ads1x15ConfigCompQueDisable // Disable comparator mode.
// Send the config value to start the ADC conversion.
// Explicitly break the 16-bit value down to a big endian pair of bytes.
if _, err = d.connection.Write([]byte{ads1x15PointerConfig, byte((config >> 8) & 0xFF), byte(config & 0xFF)}); err != nil {
return
}
// Wait for the ADC sample to finish based on the sample rate plus a
// small offset to be sure (0.1 millisecond).
time.Sleep(time.Duration(1000000/dataRate+100) * time.Microsecond)
// Retrieve the result.
if _, err = d.connection.Write([]byte{ads1x15PointerConversion}); err != nil {
return
}
data := make([]byte, 2)
_, err = d.connection.Read(data)
if err != nil {
return
}
voltageMultiplier, ok := d.gainVoltage[gain]
if !ok {
err = errors.New("Gain must be one of: 2/3, 1, 2, 4, 8, 16")
return
}
value = d.converter(data) * voltageMultiplier
return
}
func (d *ADS1x15Driver) checkChannel(channel int) (err error) {
if channel < 0 || channel > 3 {
err = errors.New("Invalid channel, must be between 0 and 3")
}
return
}