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