[Revised]Getting Started with STM32F103: SPI Transmit using DMA

In this revised guide on SPI with DMA on STM32F103, we shall transmit packet of data using DMA without CPU intervention.

In the previous guide (here), we took a look how to configure the SPI to transmit data using polling mode. In this guide, we shall use DMA to transfer data over SPI bus.

In this guide, we shall cover the following:

  • Enable TXDMA for SPI.
  • Configure the DMA.
  • Send data over DMA.
  • Code.
  • Results.

1. Enable TXDMA:

In order to enable DMA transmission for SPI, we need to set TXDMA bit in CR2 register as following:

C

Also, enable SPI1 interrupt in NVIC, this will be needed later as following:

C

The rest on the initialization is the same as polling mode.

C

. Configure the DMA:

Before we start configuring the DMA, we need to enable clock access to it. To find which bus the DMA is connected to, we need to check the block diagram of STM32F103 in the datasheet which states that DMA is connected to AHB bus:

Hence, we can enable it as following:

C

ow, we need to know which DMA channel is related to SPI1_TX:

From the table, we can find that Channel 3 is for SPI1_TX. Hence, we can configure the channel as following:

  • Memory increment mode.
  • Direction read from memory.
  • Transfer complete interrupt.
C

Set the peripheral address to be SPI1->DR:

C

Enable the interrupt in NVIC:

C

Within the interrupt:

Check the interrupt source if it is transfer complete:

If it is: clear pending flag and enable Tx buffer empty of SPI as following:

C

For SPI interrupt handler, we shall check if the tx buffer is empty and the SPI is not busy as following:

If those two condition met, call SPI1_TX_Complete function which is defined as weak and allow the user to overwrite this function is his firmware and disable SPI TX buffer is empty interrupt as following:

C

3. Send data over DMA:

To send data over DMA, the following steps are required:

  • Clear any pending flags.
  • Set the peripheral address.
  • Set the memory address.
  • set number of transfer.
  • Finally launch the transfer.
C

Hence, the source code as following:

C

The spi.h header file as following:

C

In main.c:

C

4. Code:

You may download the source code from here:

5. Results:

Connect logic analyzer to PA5, PA7 and PA0 and you should get the following:

Happy coding 😉

Add Comment

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