2017-12-13 23:40:44 +08:00
|
|
|
package spi
|
|
|
|
|
|
|
|
import (
|
2022-12-17 18:56:11 +08:00
|
|
|
"fmt"
|
2017-12-13 23:40:44 +08:00
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2017-12-14 03:08:31 +08:00
|
|
|
// MCP3002DriverMaxChannel is the number of channels of this A/D converter.
|
|
|
|
const MCP3002DriverMaxChannel = 2
|
2017-12-13 23:40:44 +08:00
|
|
|
|
|
|
|
// MCP3002Driver is a driver for the MCP3002 A/D converter.
|
|
|
|
type MCP3002Driver struct {
|
2022-12-17 18:56:11 +08:00
|
|
|
*Driver
|
2017-12-13 23:40:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewMCP3002Driver creates a new Gobot Driver for MCP3002 A/D converter
|
|
|
|
//
|
|
|
|
// Params:
|
|
|
|
// a *Adaptor - the Adaptor to use with this Driver
|
|
|
|
//
|
2018-04-12 02:22:59 +08:00
|
|
|
// Optional params:
|
2022-12-17 18:56:11 +08:00
|
|
|
// spi.WithBusNumber(int): bus to use with this driver
|
|
|
|
// spi.WithChipNumber(int): chip to use with this driver
|
|
|
|
// spi.WithMode(int): mode to use with this driver
|
|
|
|
// spi.WithBitCount(int): number of bits to use with this driver
|
|
|
|
// spi.WithSpeed(int64): speed in Hz to use with this driver
|
2018-04-12 02:22:59 +08:00
|
|
|
//
|
|
|
|
func NewMCP3002Driver(a Connector, options ...func(Config)) *MCP3002Driver {
|
2017-12-13 23:40:44 +08:00
|
|
|
d := &MCP3002Driver{
|
2022-12-17 18:56:11 +08:00
|
|
|
Driver: NewDriver(a, "MCP3002"),
|
2018-04-12 02:22:59 +08:00
|
|
|
}
|
|
|
|
for _, option := range options {
|
|
|
|
option(d)
|
2017-12-13 23:40:44 +08:00
|
|
|
}
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read reads the current analog data for the desired channel.
|
2022-12-17 18:56:11 +08:00
|
|
|
func (d *MCP3002Driver) Read(channel int) (int, error) {
|
2017-12-14 03:08:31 +08:00
|
|
|
if channel < 0 || channel > MCP3002DriverMaxChannel-1 {
|
2022-12-17 18:56:11 +08:00
|
|
|
return 0, fmt.Errorf("Invalid channel '%d' for read", channel)
|
2017-12-13 23:40:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
tx := make([]byte, 2)
|
|
|
|
tx[0] = 0x68 + (byte(channel) << 4)
|
|
|
|
tx[1] = 0x00
|
|
|
|
|
|
|
|
rx := make([]byte, 2)
|
|
|
|
|
2022-12-17 18:56:11 +08:00
|
|
|
if err := d.connection.ReadCommandData(tx, rx); err != nil {
|
|
|
|
return 0, err
|
2017-12-13 23:40:44 +08:00
|
|
|
}
|
|
|
|
|
2022-12-17 18:56:11 +08:00
|
|
|
return int((rx[0]&0x3))<<8 + int(rx[1]), nil
|
2017-12-13 23:40:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// AnalogRead returns value from analog reading of specified pin
|
|
|
|
func (d *MCP3002Driver) AnalogRead(pin string) (value int, err error) {
|
|
|
|
channel, _ := strconv.Atoi(pin)
|
|
|
|
value, err = d.Read(channel)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|