gobot.io/x/gobot@v1.16.0/drivers/spi/mcp3002.go (about) 1 package spi 2 3 import ( 4 "errors" 5 "strconv" 6 7 "gobot.io/x/gobot" 8 ) 9 10 // MCP3002DriverMaxChannel is the number of channels of this A/D converter. 11 const MCP3002DriverMaxChannel = 2 12 13 // MCP3002Driver is a driver for the MCP3002 A/D converter. 14 type MCP3002Driver struct { 15 name string 16 connector Connector 17 connection Connection 18 Config 19 gobot.Commander 20 } 21 22 // NewMCP3002Driver creates a new Gobot Driver for MCP3002 A/D converter 23 // 24 // Params: 25 // a *Adaptor - the Adaptor to use with this Driver 26 // 27 // Optional params: 28 // spi.WithBus(int): bus to use with this driver 29 // spi.WithChip(int): chip to use with this driver 30 // spi.WithMode(int): mode to use with this driver 31 // spi.WithBits(int): number of bits to use with this driver 32 // spi.WithSpeed(int64): speed in Hz to use with this driver 33 // 34 func NewMCP3002Driver(a Connector, options ...func(Config)) *MCP3002Driver { 35 d := &MCP3002Driver{ 36 name: gobot.DefaultName("MCP3002"), 37 connector: a, 38 Config: NewConfig(), 39 } 40 for _, option := range options { 41 option(d) 42 } 43 return d 44 } 45 46 // Name returns the name of the device. 47 func (d *MCP3002Driver) Name() string { return d.name } 48 49 // SetName sets the name of the device. 50 func (d *MCP3002Driver) SetName(n string) { d.name = n } 51 52 // Connection returns the Connection of the device. 53 func (d *MCP3002Driver) Connection() gobot.Connection { return d.connection.(gobot.Connection) } 54 55 // Start initializes the driver. 56 func (d *MCP3002Driver) Start() (err error) { 57 bus := d.GetBusOrDefault(d.connector.GetSpiDefaultBus()) 58 chip := d.GetChipOrDefault(d.connector.GetSpiDefaultChip()) 59 mode := d.GetModeOrDefault(d.connector.GetSpiDefaultMode()) 60 bits := d.GetBitsOrDefault(d.connector.GetSpiDefaultBits()) 61 maxSpeed := d.GetSpeedOrDefault(d.connector.GetSpiDefaultMaxSpeed()) 62 63 d.connection, err = d.connector.GetSpiConnection(bus, chip, mode, bits, maxSpeed) 64 if err != nil { 65 return err 66 } 67 return nil 68 } 69 70 // Halt stops the driver. 71 func (d *MCP3002Driver) Halt() (err error) { 72 return 73 } 74 75 // Read reads the current analog data for the desired channel. 76 func (d *MCP3002Driver) Read(channel int) (result int, err error) { 77 if channel < 0 || channel > MCP3002DriverMaxChannel-1 { 78 return 0, errors.New("Invalid channel for read") 79 } 80 81 tx := make([]byte, 2) 82 tx[0] = 0x68 + (byte(channel) << 4) 83 tx[1] = 0x00 84 85 rx := make([]byte, 2) 86 87 err = d.connection.Tx(tx, rx) 88 if err == nil && len(rx) == 2 { 89 result = int((rx[0]&0x3))<<8 + int(rx[2]) 90 } 91 92 return result, err 93 } 94 95 // AnalogRead returns value from analog reading of specified pin 96 func (d *MCP3002Driver) AnalogRead(pin string) (value int, err error) { 97 channel, _ := strconv.Atoi(pin) 98 value, err = d.Read(channel) 99 100 return 101 }