gobot.io/x/gobot/v2@v2.1.0/system/spi_periphio.go (about)

     1  package system
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"periph.io/x/conn/v3/physic"
     7  	xspi "periph.io/x/conn/v3/spi"
     8  	xsysfs "periph.io/x/host/v3/sysfs"
     9  )
    10  
    11  // spiPeriphIo is the implementation of the SPI interface using the periph.io sysfs implementation for Linux.
    12  type spiPeriphIo struct {
    13  	port xspi.PortCloser
    14  	dev  xspi.Conn
    15  }
    16  
    17  // newSpiPeriphIo creates and returns a new connection to a specific SPI device on a bus/chip
    18  // using the periph.io interface.
    19  func newSpiPeriphIo(busNum, chipNum, mode, bits int, maxSpeed int64) (*spiPeriphIo, error) {
    20  	p, err := xsysfs.NewSPI(busNum, chipNum)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	c, err := p.Connect(physic.Frequency(maxSpeed)*physic.Hertz, xspi.Mode(mode), bits)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	return &spiPeriphIo{port: p, dev: c}, nil
    29  }
    30  
    31  // TxRx uses the SPI device TX to send/receive data. Implements gobot.SpiSystemDevicer.
    32  func (c *spiPeriphIo) TxRx(tx []byte, rx []byte) error {
    33  	dataLen := len(rx)
    34  	if err := c.dev.Tx(tx, rx); err != nil {
    35  		return err
    36  	}
    37  	if len(rx) != dataLen {
    38  		return fmt.Errorf("Read length (%d) differ to expected (%d)", len(rx), dataLen)
    39  	}
    40  	return nil
    41  }
    42  
    43  // Close the SPI connection. Implements gobot.SpiSystemDevicer.
    44  func (c *spiPeriphIo) Close() error {
    45  	return c.port.Close()
    46  }