device method

  1. @override
SpiDevice device(
  1. int controller,
  2. int chipSelectPin,
  3. int speed,
  4. int mode,
)
override

Return the SpiDevice for communicating with the device over the specified controller and chip select, with the given speed and mode.

controller is the number of the SPI controller to which the device is connected. The Pi has 2 controllers, 0 and 1. Controller 0 is available for use on all Pi models while controller 1 is available on Pis with the expanded 40 pin header.

chipSelectPin is the physical pin number used by the controller to select the device for communication. Controller 0 has two chip select pins (physical pins 24 and 26) while controller 1 has three (physical pins 11, 12 and 36).

speed is the desired data exchange rate in Hz, for example 5000000 would be requesting a speed of 5 MHz. The actual speed is based on a 2 based division of the core clock and would typically be slightly less than the requested speed. Devices typically have a range of speeds at which they can communicate.

mode is a one of the following:

  • SPI_MODE_0 0x00 = SPI_CPHA 0 & SPI_CPOL 0
  • SPI_MODE_1 0x01 = SPI_CPHA 1 & SPI_CPOL 0
  • SPI_MODE_2 0x02 = SPI_CPHA 0 & SPI_CPOL 1
  • SPI_MODE_3 0x03 = SPI_CPHA 1 & SPI_CPOL 1 where
  • SPI_CPHA = bit 0x01 - clock phase
  • SPI_CPOL = bit 0x02 - clock polarity Different devices require different modes for proper communication. There are several other mode flags not supported at this time. See spi_device in https://www.kernel.org/doc/html/v4.16/driver-api/spi.html

Implementation

@override
SpiDevice device(int controller, int chipSelectPin, int speed, int mode) {
  if (mode < 0 || mode > 3)
    throw SpiException('Invalid mode: $mode', controller, chipSelectPin);
  var chipSelect = allocateChipSelectPin(controller, chipSelectPin);

  var fd = _dylib.setupDeviceMth(controller, chipSelect, speed, mode);
  if (fd < 0)
    throw SpiException('Device init failed: $fd', controller, chipSelectPin);

  final device = RpiSpiDevice(fd, controller, chipSelectPin, speed, _dylib);
  _devices.add(device);
  return device;
}