The SPI
class provides access to the SPI bus connected to Clock, MISO, and MOSI pins along with a designated Chip Select pin.
import SPI from "pins/spi";
The SPI constructor takes a dictionary which contains at least the frequency of the SPI device in Hertz (hz
) and a sub-object (cs
) containing the chip select pin number (pin
).
let device = new SPI({ hz:1000000, cs:{pin: 0} });
The constructor dictionary has three optional properties. The base dictionary object can contain a port
property which sets the SPI port (defaults to "HSPI"
on the ESP8266 and to HSPI_HOST
on the ESP32). The cs
sub-object can contain port
for the chip select GPIO port (defaults to NULL
), and activeHigh
to specify whether the chip select pin should be "high"
or "low"
when the SPI device is selected (defaults to "low"
).
let device = new SPI({ hz: 1000000, port: "HSPI", cs:{pin: 0, port: "PORT1", active: "high"} });
The transfer
function simultaneously writes and reads bytes to/from the target device. The buffer
parameter is required and must be an ArrayBuffer
. The provided buffer will be modified in place with the results of the transfer
operation and returned as the result. This operation is limited to 64 bytes per transfer.
By default, this function transfers the entire length of the provided buffer. An optional count
parameter specifies that only count
bytes of the buffer should be included in the transaction. If the bytes to be transferred do not come at the beginning of the buffer, the optional offset
parameter can be used to specify where in the buffer to begin. Offsets must be long-aligned (i.e. offset % 4 == 0
).
let data = new Uint8Array(10);
device.transfer(data.buffer, 4, 2);
The send
function writes bytes to the target device while discarding any data written back on to the SPI bus by the target device. The buffer
parameter is required and must be an ArrayBuffer
.
By default, this function transfers the entire length of the provided buffer. An optional count
parameter specifies that only count
bytes of the buffer should be sent. If the bytes to be sent do not come at the beginning of the buffer, the optional offset
parameter can be used to specify where in the buffer to begin. Offsets must be long-aligned (i.e. offset % 4 == 0
). The optional swapByteOrder
parameter will cause pairs of bytes to be swapped when sent (that is, the endianness of each two-byte word will be changed).
let data = new Uint8Array(10);
device.transfer(data.buffer, 4, 2, true);
The flush
function synchronously flushes the SPI bus.
device.flush();
The deactivate
function causes the SPI device's chip select pin to be deactivated. This is useful for devices that require a chip select deactivation between individual transactions.
device.deactivate();