gobot.io/x/gobot@v1.16.0/drivers/spi/spi.go (about) 1 package spi 2 3 import ( 4 "periph.io/x/periph/conn/physic" 5 xspi "periph.io/x/periph/conn/spi" 6 xsysfs "periph.io/x/periph/host/sysfs" 7 ) 8 9 const ( 10 // NotInitialized is the initial value for a bus/chip 11 NotInitialized = -1 12 ) 13 14 // Operations are the wrappers around the actual functions used by the SPI device interface 15 type Operations interface { 16 Close() error 17 Tx(w, r []byte) error 18 } 19 20 // Connector lets Adaptors provide the interface for Drivers 21 // to get access to the SPI buses on platforms that support SPI. 22 type Connector interface { 23 // GetSpiConnection returns a connection to a SPI device at the specified bus and chip. 24 // Bus numbering starts at index 0, the range of valid buses is 25 // platform specific. Same with chip numbering. 26 GetSpiConnection(busNum, chip, mode, bits int, maxSpeed int64) (device Connection, err error) 27 28 // GetSpiDefaultBus returns the default SPI bus index 29 GetSpiDefaultBus() int 30 31 // GetSpiDefaultChip returns the default SPI chip index 32 GetSpiDefaultChip() int 33 34 // GetDefaultMode returns the default SPI mode (0/1/2/3) 35 GetSpiDefaultMode() int 36 37 // GetDefaultMode returns the default SPI number of bits (8) 38 GetSpiDefaultBits() int 39 40 // GetSpiDefaultMaxSpeed returns the max SPI speed 41 GetSpiDefaultMaxSpeed() int64 42 } 43 44 // Connection is a connection to a SPI device with a specific bus/chip. 45 // Provided by an Adaptor, usually just by calling the spi package's GetSpiConnection() function. 46 type Connection Operations 47 48 // SpiConnection is the implementation of the SPI interface using the periph.io 49 // sysfs implementation for Linux. 50 type SpiConnection struct { 51 Operations 52 port xspi.PortCloser 53 dev xspi.Conn 54 bus int 55 chip int 56 bits int 57 mode int 58 maxSpeed int64 59 } 60 61 // NewConnection creates and returns a new connection to a specific 62 // spi device on a bus/chip using the periph.io interface. 63 func NewConnection(port xspi.PortCloser, conn xspi.Conn) (connection *SpiConnection) { 64 return &SpiConnection{port: port, dev: conn} 65 } 66 67 // Close the SPI connection. 68 func (c *SpiConnection) Close() error { 69 return c.port.Close() 70 } 71 72 // Tx uses the SPI device to send/receive data. 73 func (c *SpiConnection) Tx(w, r []byte) error { 74 return c.dev.Tx(w, r) 75 } 76 77 // GetSpiConnection is a helper to return a SPI device. 78 func GetSpiConnection(busNum, chipNum, mode, bits int, maxSpeed int64) (Connection, error) { 79 p, err := xsysfs.NewSPI(busNum, chipNum) 80 if err != nil { 81 return nil, err 82 } 83 c, err := p.Connect(physic.Frequency(maxSpeed)*physic.Hertz, xspi.Mode(mode), bits) 84 if err != nil { 85 return nil, err 86 } 87 return NewConnection(p, c), nil 88 }