gobot.io/x/gobot/v2@v2.1.0/drivers/spi/mcp3008.go (about) 1 package spi 2 3 import ( 4 "fmt" 5 "strconv" 6 ) 7 8 // MCP3008DriverMaxChannel is the number of channels of this A/D converter. 9 const MCP3008DriverMaxChannel = 8 10 11 // MCP3008Driver is a driver for the MCP3008 A/D converter. 12 type MCP3008Driver struct { 13 *Driver 14 } 15 16 // NewMCP3008Driver creates a new Gobot Driver for MCP3008Driver 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 NewMCP3008Driver(a Connector, options ...func(Config)) *MCP3008Driver { 29 d := &MCP3008Driver{ 30 Driver: NewDriver(a, "MCP3008"), 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 *MCP3008Driver) Read(channel int) (result int, err error) { 40 if channel < 0 || channel > MCP3008DriverMaxChannel-1 { 41 return 0, fmt.Errorf("Invalid channel '%d' for read", channel) 42 } 43 44 tx := make([]byte, 3) 45 tx[0] = 0x01 46 tx[1] = byte(8+channel) << 4 47 tx[2] = 0x00 48 49 rx := make([]byte, 3) 50 51 err = d.connection.ReadCommandData(tx, rx) 52 if err == nil && len(rx) == 3 { 53 result = int((rx[1]&0x3))<<8 + int(rx[2]) 54 } 55 56 return result, err 57 } 58 59 // AnalogRead returns value from analog reading of specified pin 60 func (d *MCP3008Driver) AnalogRead(pin string) (value int, err error) { 61 channel, _ := strconv.Atoi(pin) 62 value, err = d.Read(channel) 63 64 return 65 }