class SPI – a master-driven serial protocol¶
SPI is a serial protocol that is driven by a master. At the physical level there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is parameters to init the SPI bus:
from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0)
Only required parameter is mode, must be SPI.MASTER. Polarity can be 0 or 1, and is the level the idle clock line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively.
Additional methods for SPI:
data = spi.send_recv(b'1234')        # send 4 bytes and receive 4 bytes
buf = bytearray(4)
spi.send_recv(b'1234', buf)          # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf)              # send/recv 4 bytes from/to buf
Constructors¶
- 
class 
pyb.SPI(bus, ...) Construct an SPI object on the given bus.
buscan be only 1. With no additional parameters, the SPI object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. Seeinitfor parameters of initialisation.
Methods¶
- 
spi.deinit()¶ Turn off the SPI bus.
- 
spi.init(mode, baudrate=328125, *, polarity=1, phase=0, bits=8, nss=SPI.ACTIVE_LOW) Initialise the SPI bus with the given parameters:
modemust beSPI.MASTER.baudrateis the SCK clock rate.polaritycan be 0 or 1, and is the level the idle clock line sits at.phasecan be 0 or 1 to sample data on the first or second clock edge respectively.bitsis the width of each transfer, accepted values are 8, 16 and 32.nssis the polarity of the slave select line. Can beSPI.ACTIVE_LOWorSPI.ACTIVE_HIGH.
Note that the SPI clock frequency will not always be the requested baudrate. Printing the SPI object will show you the computed baudrate and the chosen prescaler.
- 
spi.recv(recv) Receive data on the bus:
recvcan be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled with received bytes.
Return value: if
recvis an integer then a new buffer of the bytes received, otherwise the same buffer that was passed in torecv.
- 
spi.send(send) Send data on the bus:
sendis the data to send (an integer to send, or a buffer object).
Return value:
None.
- 
spi.send_recv(send, recv=None) Send and receive data on the bus at the same time:
sendis the data to send (an integer to send, or a buffer object).recvis a mutable buffer which will be filled with received bytes. It can be the same assend, or omitted. If omitted, a new buffer will be created.
Return value: the buffer with the received bytes.