STM32 Guide: SPI
Image for post

Prerequisites

This is tutorial is not intended to be a guide for learning C language or about the STM32 platform. It’s primary target is to provide developers a concise guide about integrating peripheral modules and features into active applications.

If you are a beginner, I would recommend you look into an STM32 Project Setup guide like this one.

https://medium.com/vicara-hardware-university/smt32-project-setup-with-cubeide-947974baf713

SPI

Serial Peripheral Interface is a communication protocol for sending and receiving data between many devices in a serial and synchronous method. It can be a 4 channel or a 3-channel method depending on the users choice of configuration.

The most popular one is 3-channel, with MOSI, MISO and SCK. MOSI (Master Out Slave In), writes data to a slave device. MISO (Master In Slave Out) reads data from slave device. SCK is the clock signal which synchronizes communication between devices. Devices like IMU, Motor Control Units and Sensor interfaces use SPI.

There may also be the IRQ pin for interrupt and CS/SS for Chip Enable on SPI devices.

Image for post

SPI in STM32

The initialization process for STM32 peripherals is handled by the Cube IDE. Once that is done, the code generator gives a main.c file with the SPI_Init() function configured as per the settings you mention in the Cube IDE File.

Image for post


In the F407 Dev Kit we have SPI1 enabled by default. The generated code will therefore have SPI1_Init() function in the main.c file and also have it called.

The configuration will follow the same parameters you have set in the Peripheral Config Tab.

The generator will also create an SPI typedef handle. We can now use SPI API functions by using this handle as a reference.

SPI in STM32 can be done in 3 methods.

  1. Blocking Mode
  2. Interrupt Mode
  3. DMA Mode

SPI HAL API Functions

Transmit Data:

HAL_SPI_Transmit (SPI_HandleTypeDef *hspi, uint8_t * pData, uint16_t Size, uint32_t Timeout)

Parameters

Parameters
* hspi: pointer to a SPI_HandleTypeDef structure that contains
the configuration information for SPI module.
* pData: pointer to data buffer
* Size: amount of data to be sent
* Timeout: Timeout duration
Return values
* HAL: status

Receive Data

HAL_SPI_Receive (SPI_HandleTypeDef *hspi, uint8_t * pData, uint16_t Size, uint32_t Timeout)

Parameters

Parameters
* hspi: pointer to a SPI_HandleTypeDef structure that contains
the configuration information for SPI module.
* pData: pointer to data buffer
* Size: amount of data to be received
* Timeout: Timeout duration
Return values
* HAL: status

Conclusion

In this tutorial, we discussed the methods for using SPI API from CMSIS-HAL library for reading and writing to SPI devices.

Sources