SPI – a 3-4 wire serial protocol

SPI is a serial protocol that has exclusive pins for data in and out of the master. It is typically faster than I2C because a separate pin is used to control the active slave rather than a transmitted address. This class only manages three of the four SPI lines: clock, MOSI, MISO. Its up to the client to manage the appropriate slave select line. (This is common because multiple slaves can share the clock, MOSI and MISO lines and therefore the hardware.)

class bitbangio.SPI(clock, MOSI=None, MISO=None)
Construct an SPI object on the given pins.
  • clock (Pin) – the pin to use for the clock.
  • MOSI (Pin) – the Master Out Slave In pin.
  • MISO (Pin) – the Master In Slave Out pin.

Turn off the SPI bus.


No-op used by Context Managers.


Automatically deinitializes the hardware when exiting a context. See Lifetime and ContextManagers for more info.

configure(*, baudrate=100000, polarity=0, phase=0, bits=8)

Configures the SPI bus. Only valid when locked.

  • baudrate (int) – the clock rate in Hertz
  • polarity (int) – the base state of the clock line (0 or 1)
  • phase (int) – the edge of the clock that data is captured. First (0) or second (1). Rising or falling depends on clock polarity.
  • bits (int) – the number of bits per word

Attempts to grab the SPI lock. Returns True on success.

Returns:True when lock has been grabbed
Return type:bool

Releases the SPI lock.


Write the data contained in buf. Requires the SPI being locked. If the buffer is empty, nothing happens.


Read into the buffer specified by buf while writing zeroes. Requires the SPI being locked. If the number of bytes to read is 0, nothing happens.

write_readinto(buffer_out, buffer_in, *, out_start=0, out_end=len(buffer_out), in_start=0, in_end=len(buffer_in))

Write out the data in buffer_out while simultaneously reading data into buffer_in. The lengths of the slices defined by buffer_out[out_start:out_end] and buffer_in[in_start:in_end] must be equal. If buffer slice lengths are both 0, nothing happens.

  • buffer_out (bytearray) – Write out the data in this buffer
  • buffer_in (bytearray) – Read data into this buffer
  • out_start (int) – Start of the slice of buffer_out to write out: buffer_out[out_start:out_end]
  • out_end (int) – End of the slice; this index is not included
  • in_start (int) – Start of the slice of buffer_in to read into: buffer_in[in_start:in_end]
  • in_end (int) – End of the slice; this index is not included