gobot.io/x/gobot/v2@v2.1.0/drivers/spi/mcp3002.go (about) 1 package spi 2 3 import ( 4 "fmt" 5 "strconv" 6 ) 7 8 // MCP3002DriverMaxChannel is the number of channels of this A/D converter. 9 const MCP3002DriverMaxChannel = 2 10 11 // MCP3002Driver is a driver for the MCP3002 A/D converter. 12 type MCP3002Driver struct { 13 *Driver 14 } 15 16 // NewMCP3002Driver creates a new Gobot Driver for MCP3002 A/D converter 17 // 18 // Params: 19 // a *Adaptor - the Adaptor to use with this Driver 20 // 21 // Optional params: 22 // spi.WithBusNumber(int): bus to use with this driver 23 // spi.WithChipNumber(int): chip to use with this driver 24 // spi.WithMode(int): mode to use with this driver 25 // spi.WithBitCount(int): number of bits to use with this driver 26 // spi.WithSpeed(int64): speed in Hz to use with this driver 27 // 28 func NewMCP3002Driver(a Connector, options ...func(Config)) *MCP3002Driver { 29 d := &MCP3002Driver{ 30 Driver: NewDriver(a, "MCP3002"), 31 } 32 for _, option := range options { 33 option(d) 34 } 35 return d 36 } 37 38 // Read reads the current analog data for the desired channel. 39 func (d *MCP3002Driver) Read(channel int) (int, error) { 40 if channel < 0 || channel > MCP3002DriverMaxChannel-1 { 41 return 0, fmt.Errorf("Invalid channel '%d' for read", channel) 42 } 43 44 tx := make([]byte, 2) 45 tx[0] = 0x68 + (byte(channel) << 4) 46 tx[1] = 0x00 47 48 rx := make([]byte, 2) 49 50 if err := d.connection.ReadCommandData(tx, rx); err != nil { 51 return 0, err 52 } 53 54 return int((rx[0]&0x3))<<8 + int(rx[1]), nil 55 } 56 57 // AnalogRead returns value from analog reading of specified pin 58 func (d *MCP3002Driver) AnalogRead(pin string) (value int, err error) { 59 channel, _ := strconv.Atoi(pin) 60 value, err = d.Read(channel) 61 62 return 63 }