Bare-Metal STM32: Setting Up And Using SPI

The Serial Peripheral Interface (SPI) interface was initially standardized by Motorola in 1979 for short-distance communication in embedded systems. In its most common four-wire configuration, full-duplex data transfer is possible on the two data (MOSI, MISO) lines with data rates well exceeding 10 Mb/s. This makes SPI suitable for high-bandwidth, full-duplex applications like SD storage cards and large resolution, high-refresh displays.


STM32 devices come with a variable number of SPI peripherals, two in the F042 at 18 Mb/s and five in the F411. Across the STM32 families, the SPI peripheral is relatively similar, with fairly minor differences in the register layout. In this article we’ll look at configuring an SPI peripheral in master mode.



Defining SPI


One interesting and perhaps annoying factoid with SPI is that although it can support multiple devices, it does not have an addressing bus, but instead requires that a designated pin is pulled low on the device, usually called slave select (SS) or chip select (CS). With SS high, the slave device puts its other pins into high impedance mode, effectively disconnecting from the SPI lines. The STM32 SPI peripherals have a provision for a dedicated SS pin (NSS) that can streamline this process if only one device is connected. Generally you want to use GPIO pins to toggle these SS pins, with one GPIO pin per device.


For four-wire SPI the master and slave devices are thus connected with the following lines, with the SS line duplicated for each additional slave:


SCLK (serial clock, from master)
MOSI (master out, slave in)
MISO (master in, slave out)
SS (slave select)
metal stm32 setting using