Class SPI

java.lang.Object
edu.wpi.first.wpilibj.SPI
All Implemented Interfaces:
AutoCloseable

public class SPI
extends Object
implements AutoCloseable
Represents an SPI bus port.
  • Nested Class Summary

    Nested Classes 
    Modifier and Type Class Description
    static class  SPI.Mode  
    static class  SPI.Port  
  • Constructor Summary

    Constructors 
    Constructor Description
    SPI​(SPI.Port port)
    Constructor.
  • Method Summary

    Modifier and Type Method Description
    void close()  
    void configureAutoStall​(int csToSclkTicks, int stallTicks, int pow2BytesPerRead)
    Configure the Auto SPI Stall time between reads.
    void forceAutoRead()
    Force the engine to make a single transfer.
    void freeAccumulator()
    Frees the accumulator.
    void freeAuto()
    Frees the automatic SPI transfer engine.
    double getAccumulatorAverage()
    Read the average of the accumulated value.
    int getAccumulatorCount()
    Read the number of accumulated values.
    double getAccumulatorIntegratedAverage()
    Read the average of the integrated value.
    double getAccumulatorIntegratedValue()
    Read the integrated value.
    int getAccumulatorLastValue()
    Read the last value read by the accumulator engine.
    void getAccumulatorOutput​(AccumulatorResult result)
    Read the accumulated value and the number of accumulated values atomically.
    long getAccumulatorValue()
    Read the accumulated value.
    int getAutoDroppedCount()
    Get the number of bytes dropped by the automatic SPI transfer engine due to the receive buffer being full.
    int getPort()  
    void initAccumulator​(double period, int cmd, int xferSize, int validMask, int validValue, int dataShift, int dataSize, boolean isSigned, boolean bigEndian)
    Initialize the accumulator.
    void initAuto​(int bufferSize)
    Initialize automatic SPI transfer engine.
    int read​(boolean initiate, byte[] dataReceived, int size)
    Read a word from the receive FIFO.
    int read​(boolean initiate, ByteBuffer dataReceived, int size)
    Read a word from the receive FIFO.
    int readAutoReceivedData​(int[] buffer, int numToRead, double timeout)
    Read data that has been transferred by the automatic SPI transfer engine.
    int readAutoReceivedData​(ByteBuffer buffer, int numToRead, double timeout)
    Read data that has been transferred by the automatic SPI transfer engine.
    void resetAccumulator()
    Resets the accumulator to zero.
    void setAccumulatorCenter​(int center)
    Set the center value of the accumulator.
    void setAccumulatorDeadband​(int deadband)
    Set the accumulator's deadband.
    void setAccumulatorIntegratedCenter​(double center)
    Set the center value of the accumulator integrator.
    void setAutoTransmitData​(byte[] dataToSend, int zeroSize)
    Set the data to be transmitted by the engine.
    void setChipSelectActiveHigh()
    Configure the chip select line to be active high.
    void setChipSelectActiveLow()
    Configure the chip select line to be active low.
    void setClockActiveHigh()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Use setMode() instead.
    void setClockActiveLow()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Use setMode() instead.
    void setClockRate​(int hz)
    Configure the rate of the generated clock signal.
    void setLSBFirst()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Does not work, will be removed.
    void setMode​(SPI.Mode mode)
    Sets the mode for the SPI device.
    void setMSBFirst()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Does not work, will be removed.
    void setSampleDataOnLeadingEdge()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Use setMode() instead.
    void setSampleDataOnTrailingEdge()
    Deprecated, for removal: This API element is subject to removal in a future version.
    Use setMode() instead.
    void startAutoRate​(double period)
    Start running the automatic SPI transfer engine at a periodic rate.
    void startAutoTrigger​(DigitalSource source, boolean rising, boolean falling)
    Start running the automatic SPI transfer engine when a trigger occurs.
    void stopAuto()
    Stop running the automatic SPI transfer engine.
    int transaction​(byte[] dataToSend, byte[] dataReceived, int size)
    Perform a simultaneous read/write transaction with the device.
    int transaction​(ByteBuffer dataToSend, ByteBuffer dataReceived, int size)
    Perform a simultaneous read/write transaction with the device.
    int write​(byte[] dataToSend, int size)
    Write data to the peripheral device.
    int write​(ByteBuffer dataToSend, int size)
    Write data to the peripheral device.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • SPI

      public SPI​(SPI.Port port)
      Constructor.
      Parameters:
      port - the physical SPI port
  • Method Details

    • getPort

      public int getPort()
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
    • setClockRate

      public final void setClockRate​(int hz)
      Configure the rate of the generated clock signal. The default value is 500,000 Hz. The maximum value is 4,000,000 Hz.
      Parameters:
      hz - The clock rate in Hertz.
    • setMSBFirst

      @Deprecated(since="2023", forRemoval=true) public final void setMSBFirst()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Does not work, will be removed.
      Configure the order that bits are sent and received on the wire to be the most significant bit first.
    • setLSBFirst

      @Deprecated(since="2023", forRemoval=true) public final void setLSBFirst()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Does not work, will be removed.
      Configure the order that bits are sent and received on the wire to be the least significant bit first.
    • setClockActiveLow

      @Deprecated(since="2023", forRemoval=true) public final void setClockActiveLow()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use setMode() instead.
      Configure the clock output line to be active low. This is sometimes called clock polarity high or clock idle high.
    • setClockActiveHigh

      @Deprecated(since="2023", forRemoval=true) public final void setClockActiveHigh()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use setMode() instead.
      Configure the clock output line to be active high. This is sometimes called clock polarity low or clock idle low.
    • setSampleDataOnLeadingEdge

      @Deprecated(since="2023", forRemoval=true) public final void setSampleDataOnLeadingEdge()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use setMode() instead.
      Configure that the data is stable on the leading edge and the data changes on the trailing edge.
    • setSampleDataOnTrailingEdge

      @Deprecated(since="2023", forRemoval=true) public final void setSampleDataOnTrailingEdge()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use setMode() instead.
      Configure that the data is stable on the trailing edge and the data changes on the leading edge.
    • setMode

      public final void setMode​(SPI.Mode mode)
      Sets the mode for the SPI device.

      Mode 0 is Clock idle low, data sampled on rising edge.

      Mode 1 is Clock idle low, data sampled on falling edge.

      Mode 2 is Clock idle high, data sampled on falling edge.

      Mode 3 is Clock idle high, data sampled on rising edge.

      Parameters:
      mode - The mode to set.
    • setChipSelectActiveHigh

      public final void setChipSelectActiveHigh()
      Configure the chip select line to be active high.
    • setChipSelectActiveLow

      public final void setChipSelectActiveLow()
      Configure the chip select line to be active low.
    • write

      public int write​(byte[] dataToSend, int size)
      Write data to the peripheral device. Blocks until there is space in the output FIFO.

      If not running in output only mode, also saves the data received on the CIPO input during the transfer into the receive FIFO.

      Parameters:
      dataToSend - The buffer containing the data to send.
      size - The number of bytes to send.
      Returns:
      Number of bytes written or -1 on error.
    • write

      public int write​(ByteBuffer dataToSend, int size)
      Write data to the peripheral device. Blocks until there is space in the output FIFO.

      If not running in output only mode, also saves the data received on the CIPO input during the transfer into the receive FIFO.

      Parameters:
      dataToSend - The buffer containing the data to send.
      size - The number of bytes to send.
      Returns:
      Number of bytes written or -1 on error.
    • read

      public int read​(boolean initiate, byte[] dataReceived, int size)
      Read a word from the receive FIFO.

      Waits for the current transfer to complete if the receive FIFO is empty.

      If the receive FIFO is empty, there is no active transfer, and initiate is false, errors.

      Parameters:
      initiate - If true, this function pushes "0" into the transmit buffer and initiates a transfer. If false, this function assumes that data is already in the receive FIFO from a previous write.
      dataReceived - Buffer in which to store bytes read.
      size - Number of bytes to read.
      Returns:
      Number of bytes read or -1 on error.
    • read

      public int read​(boolean initiate, ByteBuffer dataReceived, int size)
      Read a word from the receive FIFO.

      Waits for the current transfer to complete if the receive FIFO is empty.

      If the receive FIFO is empty, there is no active transfer, and initiate is false, errors.

      Parameters:
      initiate - If true, this function pushes "0" into the transmit buffer and initiates a transfer. If false, this function assumes that data is already in the receive FIFO from a previous write.
      dataReceived - The buffer to be filled with the received data.
      size - The length of the transaction, in bytes
      Returns:
      Number of bytes read or -1 on error.
    • transaction

      public int transaction​(byte[] dataToSend, byte[] dataReceived, int size)
      Perform a simultaneous read/write transaction with the device.
      Parameters:
      dataToSend - The data to be written out to the device
      dataReceived - Buffer to receive data from the device
      size - The length of the transaction, in bytes
      Returns:
      TODO
    • transaction

      public int transaction​(ByteBuffer dataToSend, ByteBuffer dataReceived, int size)
      Perform a simultaneous read/write transaction with the device.
      Parameters:
      dataToSend - The data to be written out to the device.
      dataReceived - Buffer to receive data from the device.
      size - The length of the transaction, in bytes
      Returns:
      TODO
    • initAuto

      public void initAuto​(int bufferSize)
      Initialize automatic SPI transfer engine.

      Only a single engine is available, and use of it blocks use of all other chip select usage on the same physical SPI port while it is running.

      Parameters:
      bufferSize - buffer size in bytes
    • freeAuto

      public void freeAuto()
      Frees the automatic SPI transfer engine.
    • setAutoTransmitData

      public void setAutoTransmitData​(byte[] dataToSend, int zeroSize)
      Set the data to be transmitted by the engine.

      Up to 16 bytes are configurable, and may be followed by up to 127 zero bytes.

      Parameters:
      dataToSend - data to send (maximum 16 bytes)
      zeroSize - number of zeros to send after the data
    • startAutoRate

      public void startAutoRate​(double period)
      Start running the automatic SPI transfer engine at a periodic rate.

      initAuto(int) and setAutoTransmitData(byte[], int) must be called before calling this function.

      Parameters:
      period - period between transfers, in seconds (us resolution)
    • startAutoTrigger

      public void startAutoTrigger​(DigitalSource source, boolean rising, boolean falling)
      Start running the automatic SPI transfer engine when a trigger occurs.

      initAuto(int) and setAutoTransmitData(byte[], int) must be called before calling this function.

      Parameters:
      source - digital source for the trigger (may be an analog trigger)
      rising - trigger on the rising edge
      falling - trigger on the falling edge
    • stopAuto

      public void stopAuto()
      Stop running the automatic SPI transfer engine.
    • forceAutoRead

      public void forceAutoRead()
      Force the engine to make a single transfer.
    • readAutoReceivedData

      public int readAutoReceivedData​(ByteBuffer buffer, int numToRead, double timeout)
      Read data that has been transferred by the automatic SPI transfer engine.

      Transfers may be made a byte at a time, so it's necessary for the caller to handle cases where an entire transfer has not been completed.

      Each received data sequence consists of a timestamp followed by the received data bytes, one byte per word (in the least significant byte). The length of each received data sequence is the same as the combined size of the data and zeroSize set in setAutoTransmitData().

      Blocks until numToRead words have been read or timeout expires. May be called with numToRead=0 to retrieve how many words are available.

      Parameters:
      buffer - buffer where read words are stored
      numToRead - number of words to read
      timeout - timeout in seconds (ms resolution)
      Returns:
      Number of words remaining to be read
    • readAutoReceivedData

      public int readAutoReceivedData​(int[] buffer, int numToRead, double timeout)
      Read data that has been transferred by the automatic SPI transfer engine.

      Transfers may be made a byte at a time, so it's necessary for the caller to handle cases where an entire transfer has not been completed.

      Each received data sequence consists of a timestamp followed by the received data bytes, one byte per word (in the least significant byte). The length of each received data sequence is the same as the combined size of the data and zeroSize set in setAutoTransmitData().

      Blocks until numToRead words have been read or timeout expires. May be called with numToRead=0 to retrieve how many words are available.

      Parameters:
      buffer - array where read words are stored
      numToRead - number of words to read
      timeout - timeout in seconds (ms resolution)
      Returns:
      Number of words remaining to be read
    • getAutoDroppedCount

      public int getAutoDroppedCount()
      Get the number of bytes dropped by the automatic SPI transfer engine due to the receive buffer being full.
      Returns:
      Number of bytes dropped
    • configureAutoStall

      public void configureAutoStall​(int csToSclkTicks, int stallTicks, int pow2BytesPerRead)
      Configure the Auto SPI Stall time between reads.
      Parameters:
      csToSclkTicks - the number of ticks to wait before asserting the cs pin
      stallTicks - the number of ticks to stall for
      pow2BytesPerRead - the number of bytes to read before stalling
    • initAccumulator

      public void initAccumulator​(double period, int cmd, int xferSize, int validMask, int validValue, int dataShift, int dataSize, boolean isSigned, boolean bigEndian)
      Initialize the accumulator.
      Parameters:
      period - Time between reads
      cmd - SPI command to send to request data
      xferSize - SPI transfer size, in bytes
      validMask - Mask to apply to received data for validity checking
      validValue - After validMask is applied, required matching value for validity checking
      dataShift - Bit shift to apply to received data to get actual data value
      dataSize - Size (in bits) of data field
      isSigned - Is data field signed?
      bigEndian - Is device big endian?
    • freeAccumulator

      public void freeAccumulator()
      Frees the accumulator.
    • resetAccumulator

      public void resetAccumulator()
      Resets the accumulator to zero.
    • setAccumulatorCenter

      public void setAccumulatorCenter​(int center)
      Set the center value of the accumulator.

      The center value is subtracted from each value before it is added to the accumulator. This is used for the center value of devices like gyros and accelerometers to make integration work and to take the device offset into account when integrating.

      Parameters:
      center - The accumulator's center value.
    • setAccumulatorDeadband

      public void setAccumulatorDeadband​(int deadband)
      Set the accumulator's deadband.
      Parameters:
      deadband - The accumulator's deadband.
    • getAccumulatorLastValue

      Read the last value read by the accumulator engine.
      Returns:
      The last value read by the accumulator engine.
    • getAccumulatorValue

      public long getAccumulatorValue()
      Read the accumulated value.
      Returns:
      The 64-bit value accumulated since the last Reset().
    • getAccumulatorCount

      public int getAccumulatorCount()
      Read the number of accumulated values.

      Read the count of the accumulated values since the accumulator was last Reset().

      Returns:
      The number of times samples from the channel were accumulated.
    • getAccumulatorAverage

      public double getAccumulatorAverage()
      Read the average of the accumulated value.
      Returns:
      The accumulated average value (value / count).
    • getAccumulatorOutput

      public void getAccumulatorOutput​(AccumulatorResult result)
      Read the accumulated value and the number of accumulated values atomically.

      This function reads the value and count atomically. This can be used for averaging.

      Parameters:
      result - AccumulatorResult object to store the results in.
    • setAccumulatorIntegratedCenter

      public void setAccumulatorIntegratedCenter​(double center)
      Set the center value of the accumulator integrator.

      The center value is subtracted from each value*dt before it is added to the integrated value. This is used for the center value of devices like gyros and accelerometers to take the device offset into account when integrating.

      Parameters:
      center - The accumulator integrator's center value.
    • getAccumulatorIntegratedValue

      Read the integrated value. This is the sum of (each value * time between values).
      Returns:
      The integrated value accumulated since the last Reset().
    • getAccumulatorIntegratedAverage

      Read the average of the integrated value. This is the sum of (each value times the time between values), divided by the count.
      Returns:
      The average of the integrated value accumulated since the last Reset().