-
Notifications
You must be signed in to change notification settings - Fork 110
/
mcp3008.go
39 lines (32 loc) · 974 Bytes
/
mcp3008.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
package board
import (
"context"
"go.uber.org/multierr"
)
// MCP3008AnalogReader implements a board.AnalogReader using an MCP3008 ADC via SPI.
type MCP3008AnalogReader struct {
Channel int
Bus SPI
Chip string
}
func (mar *MCP3008AnalogReader) Read(ctx context.Context, extra map[string]interface{}) (value int, err error) {
var tx [3]byte
tx[0] = 1 // start bit
tx[1] = byte((8 + mar.Channel) << 4) // single-ended
tx[2] = 0 // extra clocks to receive full 10 bits of data
bus, err := mar.Bus.OpenHandle()
if err != nil {
return 0, err
}
defer func() {
err = multierr.Combine(err, bus.Close())
}()
rx, err := bus.Xfer(ctx, 1000000, mar.Chip, 0, tx[:])
if err != nil {
return 0, err
}
// Reassemble the 10-bit value. Do not include bits before the final 10, because they contain
// garbage and might be non-zero.
val := 0x03FF & ((int(rx[1]) << 8) | int(rx[2]))
return val, nil
}