-
Notifications
You must be signed in to change notification settings - Fork 110
/
mcp3008.go
63 lines (53 loc) · 1.89 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package board
import (
"context"
"go.uber.org/multierr"
"go.viam.com/utils"
)
// MCP3008AnalogReader implements a board.AnalogReader using an MCP3008 ADC via SPI.
type MCP3008AnalogReader struct {
Channel int
Bus SPI
Chip string
}
// MCP3008AnalogConfig describes the configuration of a MCP3008 analog reader on a board.
type MCP3008AnalogConfig struct {
Name string `json:"name"`
Pin string `json:"pin"` // analog input pin on the ADC itself
SPIBus string `json:"spi_bus"` // name of the SPI bus (which is configured elsewhere in the config file)
ChipSelect string `json:"chip_select"` // the CS line for the ADC chip, typically a pin number on the board
AverageOverMillis int `json:"average_over_ms,omitempty"`
SamplesPerSecond int `json:"samples_per_sec,omitempty"`
}
// Validate ensures all parts of the config are valid.
func (config *MCP3008AnalogConfig) Validate(path string) error {
if config.Name == "" {
return utils.NewConfigValidationFieldRequiredError(path, "name")
}
return nil
}
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
}
// Close does nothing.
func (mar *MCP3008AnalogReader) Close(ctx context.Context) error {
return nil
}