class SPI – a controller-driven serial protocol — MicroPython latest documentation (original) (raw)

SPI is a serial protocol that is driven by a controller. 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.CONTROLLER, baudrate=600000, polarity=1, phase=0, crc=0x7)

Only required parameter is mode, SPI.CONTROLLER or SPI.PERIPHERAL. 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. Crc can be None for no CRC, or a polynomial specifier.

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. bus can be 1 or 2, or ‘X’ or ‘Y’. 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. See init for parameters of initialisation.

The physical pins of the SPI buses are:

At the moment, the NSS pin is not used by the SPI driver and is free for other use.

Methods

SPI.deinit()

Turn off the SPI bus.

SPI.init(mode, baudrate=328125, *, prescaler=-1, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None)

Initialise the SPI bus with the given parameters:

Note that the SPI clock frequency will not always be the requested baudrate. The hardware only supports baudrates that are the APB bus frequency (see pyb.freq()) divided by a prescaler, which can be 2, 4, 8, 16, 32, 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise control over the SPI clock frequency, specify prescaler instead ofbaudrate.

Printing the SPI object will show you the computed baudrate and the chosen prescaler.

SPI.recv(recv, *, timeout=5000)

Receive data on the bus:

Return value: if recv is an integer then a new buffer of the bytes received, otherwise the same buffer that was passed in to recv.

SPI.send(send, *, timeout=5000)

Send data on the bus:

Return value: None.

SPI.send_recv(send, recv=None, *, timeout=5000)

Send and receive data on the bus at the same time:

Return value: the buffer with the received bytes.

Constants

SPI.CONTROLLER

SPI.PERIPHERAL

for initialising the SPI bus to controller or peripheral mode

SPI.LSB

SPI.MSB

set the first bit to be the least or most significant bit