![](https://blog.embeddedexpert.io/wp-content/uploads/2024/06/pt156578902-100_original_arm_mcu_stm32g070kbt6_stm32g070_stm32g_lqfp_32_microcontroller.jpg-2-4-2-1.webp)
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:
![](https://blog.embeddedexpert.io/wp-content/uploads/2024/06/2024-06-08_16-23-19-1024x584.jpg)
- 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:
![](https://blog.embeddedexpert.io/wp-content/uploads/2024/05/Screenshot-2024-05-24-at-7.59.23 AM-1024x738.png)
Happy coding 😉
Add Comment