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 machine import SPI spi = SPI(0, mode=SPI.MASTER, baudrate=1000000, polarity=0, phase=0, firstbit=SPI.MSB)
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.
from machine import SPI # configure the SPI master @ 2MHz # this uses the SPI default pins for CLK, MOSI and MISO (``P10``, ``P11`` and ``P14``) spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0) spi.write(bytes([0x01, 0x02, 0x03, 0x04, 0x05])) # send 5 bytes on the bus spi.read(5) # receive 5 bytes on the bus rbuf = bytearray(5) spi.write_readinto(bytes([0x01, 0x02, 0x03, 0x04, 0x05]), rbuf) # send a receive 5 bytes
from machine import SPI # configure the SPI master @ 2MHz # this uses the SPI non-default pins for CLK, MOSI and MISO (``P19``, ``P20`` and ``P21``) spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0, pins=('P19','P20','P21')) spi.write(bytes([0x01, 0x02, 0x03, 0x04, 0x05])) # send 5 bytes on the bus spi.read(5) # receive 5 bytes on the bus rbuf = bytearray(5) spi.write_readinto(bytes([0x01, 0x02, 0x03, 0x04, 0x05]), rbuf) # send a receive 5 bytes
Construct an SPI object on the given bus. id can be only 0. With no additional parameters, the SPI object is created but not initialized (it has the settings from the last initialization of the bus, if any). If extra arguments are given, the bus is initialized. See init for parameters of initialization.
id
Initialize the SPI bus with the given parameters:
mode
baudrate
polarity
phase
bits
firstbit
pins
P10
P11
P14
Turn off the SPI bus.
Write the data contained in buf. Returns the number of bytes written.
buf
Read the nbytes while writing the data specified by write. Returns the bytes read.
nbytes
write
Read into the buffer specified by buf while writing the data specified by write. Return the number of bytes read.
Write from write_buf and read into read_buf. Both buffers must have the same length. Returns the number of bytes written
write_buf
read_buf
SPI.MASTER
SPI.MSB
SPI.LSB