Getting Started with STM32G0 and STM32CubeIDE: SPI RX DMA

In the previous guide (here), we took a look how to transmit data over SPI bus using DMA. In this guide, we shall use the DMA to receive data over SPI from a slave device (MPU9250) in this case.

In this guide, we shall cover the following:

  • Enabling the DMA RX for SPI.
  • Modification for MPU9250 source code.
  • Results.

1. Enabling the DMA RX for SPI:

By continuing from this guide.

Enable the DMA for reception of data as following:

  • From communication select SPI.
  • Select DMA Settings.
  • Add SPI_RX.
  • Leave everything as default.

Also, enable UART, for more details, please refer to this guide.

Save the project and this should generate the code.

2. Modification of MPU9250 Source Code:

From this guide, we shall modify the source code as following:

In the declared variables, add the following variable:

volatile uint8_t rx_Done;

Since this variable changes in the interrupt, we need to set it as volatile to prevent compiler optimization.

At the end of the source code, add the following function:

void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
	rx_Done=1;

}

This function shall be called when the DMA received the data from the SPI bus.

In MPU9250_accelUpdate function, we shall replace this function:

HAL_SPI_Receive(&hspi1, accelBuf, 6, 100);

With this function:

HAL_SPI_Receive_DMA(&hspi1, accelBuf, 6);

This function shall received the data over SPI using DMA.

Wait for the DMA to finish transfer:

	while(rx_Done==0);
	rx_Done=0;

In MPU9250_gyroUpdate function:

Replace this function

HAL_SPI_Receive(&hspi1, gyroBuf, 6, 100);

With this function:

HAL_SPI_Receive_DMA(&hspi1, gyroBuf, 6);

Also, wait for the DMA to finish transfer:

void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
	rx_Done=1;

}

Thats all for the modification.

3. Results:

Open your serial monitor application, select the COM port and set the baud to be 115200 and you should get the following:

Happy coding 😉

Add Comment

Your email address will not be published. Required fields are marked *