Skip to content
systemcoding.dev
Embedded

Copy Memory to Memory With STM32 DMA

Copy and fill memory blocks with the STM32F4 DMA2 controller using HAL_DMA_Start_IT or polling, with the FIFO setting it requires and the common mistakes.

8 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the STMicroelectronics, Arm and C logos.

Copying a buffer with DMA is the smallest complete DMA program, which makes it the best place to learn the controller before a peripheral and its request lines enter the picture. On the STM32F4 the job takes one stream, one configuration structure and two calls. This post walks through it on an STM32F407 with STM32CubeF4 firmware V1.28 and the HAL: a word-by-word copy, a polled and an interrupt-driven way to wait for it, a fill that writes one value across a whole block, and the five mistakes that make a memory-to-memory transfer silently do nothing. The behavior described comes from the DMA chapter of the STM32F4 reference manual RM0090.

The DMA overview explains what the controller is doing. Here we only configure it.

Which controller can do it

The STM32F4 has two DMA controllers, DMA1 and DMA2, each with eight streams. Only DMA2 can perform memory-to-memory transfers. DMA1 is wired to the APB1 peripherals and has no path for a transfer where both ends are memory, so a configuration for it is invalid. Use any stream of DMA2 for the copy. This example uses stream 0.

Two other rules from the reference manual shape the configuration.

  • In memory-to-memory mode, the FIFO must be enabled. Direct mode, which passes each unit straight through, applies only between a peripheral and memory. Leaving FIFOMode at its default of disabled is the most common reason a memory copy does not start.

  • In this mode the DMA "peripheral" side is the source and the "memory" side is the destination. The names are historical, taken from the peripheral-to-memory case, and they read backwards when both ends are RAM.

A word copy with an interrupt

The configuration for 32-bit words, with both addresses advancing:

dma_copy.cc
#include "stm32f4xx_hal.h"

#define WORDS 128

DMA_HandleTypeDef hdma_copy;
volatile uint8_t copy_done;
volatile uint8_t copy_error;

static uint32_t src_buf[WORDS];
static uint32_t dst_buf[WORDS];

static void on_complete(DMA_HandleTypeDef *h) { (void)h; copy_done = 1; }
static void on_error(DMA_HandleTypeDef *h)    { (void)h; copy_error = 1; }

void dma_copy_init(void) {
    __HAL_RCC_DMA2_CLK_ENABLE();

    hdma_copy.Instance                 = DMA2_Stream0;
    hdma_copy.Init.Channel             = DMA_CHANNEL_0;
    hdma_copy.Init.Direction           = DMA_MEMORY_TO_MEMORY;
    hdma_copy.Init.PeriphInc           = DMA_PINC_ENABLE;     // source advances
    hdma_copy.Init.MemInc              = DMA_MINC_ENABLE;     // destination advances
    hdma_copy.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    hdma_copy.Init.MemDataAlignment    = DMA_MDATAALIGN_WORD;
    hdma_copy.Init.Mode                = DMA_NORMAL;
    hdma_copy.Init.Priority            = DMA_PRIORITY_LOW;
    hdma_copy.Init.FIFOMode            = DMA_FIFOMODE_ENABLE;
    hdma_copy.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
    hdma_copy.Init.MemBurst            = DMA_MBURST_SINGLE;
    hdma_copy.Init.PeriphBurst         = DMA_PBURST_SINGLE;
    HAL_DMA_Init(&hdma_copy);

    HAL_DMA_RegisterCallback(&hdma_copy, HAL_DMA_XFER_CPLT_CB_ID,  on_complete);
    HAL_DMA_RegisterCallback(&hdma_copy, HAL_DMA_XFER_ERROR_CB_ID, on_error);

    HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn);
}

void DMA2_Stream0_IRQHandler(void) {
    HAL_DMA_IRQHandler(&hdma_copy);
}

HAL_StatusTypeDef dma_copy_words(const uint32_t *src, uint32_t *dst, uint32_t words) {
    copy_done = 0;
    copy_error = 0;
    return HAL_DMA_Start_IT(&hdma_copy, (uint32_t)src, (uint32_t)dst, words);
}

HAL_DMA_Start_IT takes the source address, the destination address and the number of units, where a unit is the data width you configured. For 32-bit words, 128 units are 512 bytes. Passing a byte count where the controller expects word units copies four times too much and overwrites whatever follows the buffer, which is the most damaging of the mistakes here. The count register holds 16 bits, so a single transfer is at most 65,535 units; a larger block needs several transfers.

A short test program fills the source, runs the copy and checks the result:

main.cc
#include <stdio.h>

int main(void) {
    HAL_Init();
    SystemClock_Config();
    dma_copy_init();

    for (uint32_t i = 0; i < WORDS; i++) {
        src_buf[i] = 0xC0DE0000u | i;
        dst_buf[i] = 0xFFFFFFFFu;
    }

    dma_copy_words(src_buf, dst_buf, WORDS);
    while (!copy_done && !copy_error) { }

    uint32_t mismatches = 0;
    for (uint32_t i = 0; i < WORDS; i++) {
        if (dst_buf[i] != src_buf[i]) mismatches++;
    }
    printf("done=%u error=%u mismatches=%lu dst[0]=0x%lX dst[127]=0x%lX\r\n",
           copy_done, copy_error, (unsigned long)mismatches,
           (unsigned long)dst_buf[0], (unsigned long)dst_buf[WORDS - 1]);
    while (1) { }
}
Text
done=1 error=0 mismatches=0 dst[0]=0xC0DE0000 dst[127]=0xC0DE007F

The destination was prefilled with 0xFFFFFFFF before the copy, so any slot the DMA did not write would still read that value. Prefilling with a recognizable pattern is the cheapest test that a transfer actually ran.

Waiting by polling instead

An interrupt handler is more machinery than a one-off copy needs. HAL_DMA_Start begins the transfer without enabling interrupts, and HAL_DMA_PollForTransfer waits for completion, with a timeout in milliseconds.

poll_copy.cc
HAL_StatusTypeDef dma_copy_blocking(const uint32_t *src, uint32_t *dst, uint32_t words) {
    if (HAL_DMA_Start(&hdma_copy, (uint32_t)src, (uint32_t)dst, words) != HAL_OK) {
        return HAL_ERROR;
    }
    return HAL_DMA_PollForTransfer(&hdma_copy, HAL_DMA_FULL_TRANSFER, 10);
}

Polling blocks the CPU for the duration of the copy, which defeats the usual purpose of DMA, so use it where the point is the code's simplicity, such as in start-up code or in a test. The timeout of 10 milliseconds is an upper bound for the call, and a result of HAL_TIMEOUT means the transfer did not finish in that time, which for a small block indicates a configuration fault.

Filling memory

A fill writes one value across a block, the job of memset generalized to words. DMA does it by turning source increment off. The source address then stays on one word, and every unit reads that same word and writes it to the next destination slot.

dma_fill.cc
static uint32_t fill_value;

HAL_StatusTypeDef dma_fill_words(uint32_t *dst, uint32_t value, uint32_t words) {
    fill_value = value;
    hdma_copy.Init.PeriphInc = DMA_PINC_DISABLE;   // source address fixed
    HAL_DMA_Init(&hdma_copy);
    return HAL_DMA_Start(&hdma_copy, (uint32_t)&fill_value, (uint32_t)dst, words);
}

With a value of 0xDEADBEEF and 64 words, after completion every word of the destination reads 0xDEADBEEF:

Text
dst[0]=0xDEADBEEF dst[31]=0xDEADBEEF dst[63]=0xDEADBEEF

The source variable must stay valid until the transfer ends, which is why it is static here. Re-initializing the stream to change PeriphInc is acceptable between transfers, and not while one is running. For repeated use of both a copy and a fill, keep two handles on two streams, so neither needs reconfiguring.

The mistakes that silently do nothing

SymptomCause
No transfer, no errorFIFO left disabled in memory-to-memory mode
Hangs in HAL_DMA_PollForTransferDMA1 stream used, or the stream's clock not enabled
Destination holds a repeated valueSource increment off, which is correct for a fill and wrong for a copy
Copy is four times too long and corrupts memoryByte count passed to a word transfer
Transfer error flagSource or destination in core-coupled RAM, which DMA cannot reach
Transfer error on a half-word copyOdd address with a 16-bit width, an alignment violation

The core-coupled memory trap is specific to the F4 family. If your linker script places a buffer in the 64 KB of CCM RAM at 0x10000000, which holds stacks and some variables in many projects, a DMA transfer touching it fails with a transfer error, and with the interrupt disabled you see nothing. Keep DMA buffers in main SRAM.

Is it worth it for a copy

For small blocks, no. A CPU copy loop moves a word in a handful of cycles, and DMA adds the setup writes, the arbitration and the completion handling. The break-even depends on block size, clock speed and flash wait states, and we do not quote a number because it differs on every part; measure it on yours with the cycle counter before you commit to DMA for copies. The honest summary is that DMA wins for blocks in the kilobyte range and above, and when the CPU has something useful to do in the meantime. A large frame buffer copy while the CPU computes the next frame is the typical good case. A 16-byte structure is not.

Copying more than 65,535 units

The count register is 16 bits, so one transfer tops out at 65,535 units. A larger block, such as a 200 KB frame buffer, needs a loop of transfers, each started from the completion callback of the one before. The callback advances the source and destination pointers by the chunk size and starts the next chunk until the remainder is zero.

big_copy.cc
static const uint32_t *big_src;
static uint32_t       *big_dst;
static uint32_t        big_left;
static volatile uint8_t big_done;

#define CHUNK 32768u    // words per transfer, well under the 65,535 limit

static void start_chunk(void) {
    uint32_t n = big_left < CHUNK ? big_left : CHUNK;
    HAL_DMA_Start_IT(&hdma_copy, (uint32_t)big_src, (uint32_t)big_dst, n);
    big_src += n;
    big_dst += n;
    big_left -= n;
}

static void on_chunk_done(DMA_HandleTypeDef *h) {
    (void)h;
    if (big_left) start_chunk(); else big_done = 1;
}

Register on_chunk_done as the complete callback in place of on_complete, set the three pointers and the remaining count, and call start_chunk once. For 100,000 words the sequence is three full chunks of 32,768 words and one of 1,696, which is 100,000 - 3 * 32,768.

Text
chunk 1: 32768 words
chunk 2: 32768 words
chunk 3: 32768 words
chunk 4: 1696 words

Starting the next chunk from inside the interrupt callback is fine, since HAL_DMA_Start_IT only writes registers. The hand-off leaves a gap of a few cycles between chunks, which does not matter for a copy.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.