Skip to content
systemcoding.dev
Embedded

The Complete Guide to DMA on Microcontrollers

Learn how DMA controllers move data without the CPU, from memory copies to ADC, UART and timer transfers, on STM32, RP2040 and ESP32, and the pitfalls to avoid.

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

A microcontroller spends a surprising share of its life moving numbers from one place to another. A UART receives a byte and the CPU copies it into a buffer. An ADC finishes a conversion and the CPU copies the result into an array. A display needs a frame and the CPU copies a few kilobytes into the right register, one word at a time. None of that is computation. It is data movement, and a direct memory access controller, DMA, does it without running a single CPU instruction. The CPU configures a transfer, goes on with other work, and gets a flag or an interrupt when the data has arrived.

This guide builds DMA from its parts upward. It starts with what a DMA controller is made of, runs a first transfer on an STM32 and an RP2040, then adds the pieces that make DMA useful in real firmware: peripheral triggers, circular buffers, half-transfer events, chaining, request routing, cache coherency and bus arbitration. The STM32 examples use an STM32F407 with the STM32CubeF4 firmware package V1.28 and its HAL, the RP2040 examples use Pico SDK 2.1, and the ESP32 notes use ESP-IDF 5.4. The most useful primary sources are the DMA chapter of the STM32F4 reference manual RM0090, the DMA section of the RP2040 datasheet and the ESP-IDF memory allocation documentation.

The problem DMA solves

Take a UART running at 115,200 baud. Each byte takes ten bit times, so about 11,520 bytes arrive per second. If the CPU handles each byte in an interrupt, the processor takes 11,520 interrupts per second. Each one costs a context save, a handler body and a restore, on the order of a hundred cycles, so an interrupt-driven receive takes over a million cycles per second. On a 168 MHz core that is under one percent, which sounds cheap until you run four UARTs, an ADC at 100 kilosamples per second and an SPI display on the same part, and the interrupt latency starts to reach everything else.

DMA changes the cost model. A single interrupt fires when a whole buffer, say 256 bytes, is full, not for each byte. The per-byte work moves to hardware that does nothing else. The same 11,520 bytes per second turns into 45 interrupts per second at the same total throughput, and a faster peripheral scales the same way, because the DMA controller transfers a word per bus cycle and never needs a context switch.

Three situations make DMA worth the setup effort:

  1. Streams of data from a peripheral at a regular rate, such as ADC samples, audio over I2S, or SPI data from a sensor.

  2. Bulk copies, such as filling a display buffer or clearing a large array, which would otherwise occupy the CPU for the full copy.

  3. Timing-critical output, such as a waveform fed to a DAC or the pattern fed to a timer's registers, where an interrupt's jitter would show in the signal.

What a DMA controller is made of

Strip away the vendor names and every DMA controller has the same parts. Learn them once and any chip's reference manual becomes readable.

PartWhat it isTypical register
Channel or streamOne independent transfer engine; a controller has severalOne register set per channel
Source addressWhere to read fromPAR or M0AR on STM32, read address on RP2040
Destination addressWhere to write toThe other address register
Transfer countHow many units to moveNDTR on STM32, TRANS_COUNT on RP2040
Data widthSize of one unit: byte, half-word or wordSize fields in the control register
Address incrementWhether each address advances after a unitIncrement bits, one per side
Trigger or requestThe event that starts each unitChannel selection, request number
PriorityWhich channel wins when several are readyPriority bits
InterruptsEvents reported to the CPUHalf, complete and error flags

The most important idea in that table is the pairing of an address with an increment setting. A peripheral data register sits at one fixed address. When you read ADC results from it, you want the source to stay put and the destination to advance through an array, so the source has increment off and the destination has increment on. A memory-to-memory copy advances both. A fill that writes the same value everywhere advances only the destination. Get an increment bit wrong and the transfer still runs, with every sample landing in the same array slot, which looks like a peripheral that always returns the latest value.

Direction and mode

A transfer has a direction, which says which side is the peripheral and which is memory, and a mode, which says what happens when the count reaches zero.

  • Peripheral to memory: ADC results, UART or SPI receive, timer capture values.

  • Memory to peripheral: UART or SPI transmit, DAC samples, timer register updates.

  • Memory to memory: bulk copies. Many controllers restrict this to specific channels. On the STM32F4, only DMA2 supports it.

In normal mode the transfer runs count units, raises its complete flag and stops. Software must re-arm it. In circular mode the controller reloads the count and the starting addresses after the last unit and starts over, so a stream such as ADC sampling keeps filling the same buffer forever, and you read it behind the write position. Circular mode is what makes continuous acquisition possible without gaps between buffers.

A first transfer: memory to memory on STM32

The simplest DMA program copies an array to another array. On the STM32F407, DMA2 stream 0 can do memory-to-memory transfers. The controller also requires its FIFO to be enabled for this direction, because direct mode, which passes each unit straight through, only works between a peripheral and memory.

dma_copy.cc
#include <stdio.h>
#include "stm32f4xx_hal.h"

#define WORDS 64

DMA_HandleTypeDef hdma;
volatile uint8_t copy_done;

static uint32_t src[WORDS];
static uint32_t dst[WORDS];

static void transfer_complete(DMA_HandleTypeDef *h) {
    (void)h;
    copy_done = 1;
}

void dma_copy_init(void) {
    __HAL_RCC_DMA2_CLK_ENABLE();

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

    HAL_DMA_RegisterCallback(&hdma, HAL_DMA_XFER_CPLT_CB_ID, transfer_complete);
    HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 1, 0);
    HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn);
}

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

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

    for (int i = 0; i < WORDS; i++) src[i] = 0x1000u + (uint32_t)i;

    copy_done = 0;
    HAL_DMA_Start_IT(&hdma, (uint32_t)src, (uint32_t)dst, WORDS);
    while (!copy_done) { }

    printf("dst[0]=0x%lX dst[63]=0x%lX\r\n",
           (unsigned long)dst[0], (unsigned long)dst[WORDS - 1]);
    while (1) { }
}

For this direction the HAL's naming is confusing: "peripheral" means the source and "memory" means the destination, and HAL_DMA_Start_IT takes the source first. Both sides advance, both are word-sized, and the count is in units of that size, not bytes, so 64 units of 4 bytes copy 256 bytes. When the copy ends, the controller sets its transfer-complete flag, the handler calls your callback, and the main loop proceeds.

Text
dst[0]=0x1000 dst[63]=0x103F

The result is what you would get from a loop, but the CPU did nothing during the copy except wait here, and it could have been doing real work. The memory-to-memory post adds a polling variant and measures when DMA is worth it for a copy.

The same operation on the RP2040 uses the channel configuration structure of the Pico SDK. There is no direction setting there, since a DMA channel always reads from a read address and writes to a write address, and the increment flags and the trigger select what kind of transfer it is.

dma_copy_pico.cc
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/dma.h"

#define WORDS 64

static uint32_t src[WORDS];
static uint32_t dst[WORDS];

int main(void) {
    stdio_init_all();
    for (int i = 0; i < WORDS; i++) src[i] = 0x1000u + (uint32_t)i;

    int ch = dma_claim_unused_channel(true);
    dma_channel_config cfg = dma_channel_get_default_config(ch);
    channel_config_set_transfer_data_size(&cfg, DMA_SIZE_32);
    channel_config_set_read_increment(&cfg, true);
    channel_config_set_write_increment(&cfg, true);

    dma_channel_configure(ch, &cfg, dst, src, WORDS, true);
    dma_channel_wait_for_finish_blocking(ch);

    printf("dst[0]=0x%lX dst[63]=0x%lX\n",
           (unsigned long)dst[0], (unsigned long)dst[WORDS - 1]);
    return 0;
}

The last argument to dma_channel_configure, true, starts the transfer immediately. The SDK function dma_claim_unused_channel reserves a free one of the twelve channels, and the claim prevents another library from using it. The RP2040 DMA post covers the configuration fields in more depth.

Why the first example is the wrong reason to use DMA

A memory copy of 256 bytes is faster on the CPU than the time it takes to set up the DMA, wait for the interrupt and return. DMA has a fixed setup cost, a few dozen cycles, and the CPU's own load and store loop on a modern core moves a word in a cycle or two. The break-even is a few hundred bytes, and varies with the part. We use memory-to-memory DMA for the large copies where it pays, such as a frame buffer of tens of kilobytes, and not for small structures. The real power of DMA is the peripheral-triggered transfer, which no CPU loop can match because the CPU cannot wait for a peripheral without either polling or taking an interrupt.

Peripheral-triggered DMA: the useful case

A peripheral that wants servicing raises a DMA request, a signal the controller watches. Each request lets one unit transfer. The CPU is not involved in any of the units, only in the setup and, if you ask for it, in an interrupt at the end or the middle of the buffer. This is the arrangement that makes a continuous ADC stream practical.

On the STM32F407, the ADC1 request is wired to DMA2 stream 0 channel 0 (and to stream 4 channel 0). The channel number selects which peripheral's request the stream listens to, so the same stream could serve a different peripheral by changing the channel. Pick the stream from the table in the reference manual; the HAL does not check that your choice is a legal pairing, and a wrong one produces a program that compiles, runs and never transfers.

adc_dma.cc
#include "stm32f4xx_hal.h"

#define BUF_LEN 256

ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
uint16_t adc_buf[BUF_LEN];

volatile uint8_t first_half_ready;
volatile uint8_t second_half_ready;

void adc_dma_start(void) {
    __HAL_RCC_DMA2_CLK_ENABLE();

    hdma_adc1.Instance                 = DMA2_Stream0;
    hdma_adc1.Init.Channel             = DMA_CHANNEL_0;
    hdma_adc1.Init.Direction           = DMA_PERIPH_TO_MEMORY;
    hdma_adc1.Init.PeriphInc           = DMA_PINC_DISABLE;
    hdma_adc1.Init.MemInc              = DMA_MINC_ENABLE;
    hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
    hdma_adc1.Init.MemDataAlignment    = DMA_MDATAALIGN_HALFWORD;
    hdma_adc1.Init.Mode                = DMA_CIRCULAR;
    hdma_adc1.Init.Priority            = DMA_PRIORITY_HIGH;
    hdma_adc1.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
    HAL_DMA_Init(&hdma_adc1);
    __HAL_LINKDMA(&hadc1, DMA_Handle, hdma_adc1);

    HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 1, 0);
    HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn);

    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buf, BUF_LEN);
}

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

void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc) {
    (void)hadc;
    first_half_ready = 1;      // adc_buf[0 .. 127] is stable
}

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) {
    (void)hadc;
    second_half_ready = 1;     // adc_buf[128 .. 255] is stable
}

The code shows the pattern that most DMA streaming uses, the half-transfer buffer. The stream is circular and writes samples in order. When it has written half the buffer, it raises the half-transfer event, and your code processes the first half while the stream fills the second. When the stream reaches the end it raises the transfer-complete event, wraps to the start, and your code processes the second half while the first is overwritten. The CPU always works on the half the DMA is not writing, and has half a buffer period to finish before the stream catches up. The circular DMA post works through the timing and the failure case when processing runs late.

A transmit example: UART and the completion callback

Sending a block of bytes over a UART by DMA turns a long blocking call into a request and a completion event. The HAL's call returns immediately.

uart_tx.cc
#include "stm32f4xx_hal.h"
#include <string.h>

extern UART_HandleTypeDef huart2;
static volatile uint8_t tx_busy;

int uart_send_async(const uint8_t *data, uint16_t len) {
    if (tx_busy) return -1;
    tx_busy = 1;
    if (HAL_UART_Transmit_DMA(&huart2, (uint8_t *)data, len) != HAL_OK) {
        tx_busy = 0;
        return -1;
    }
    return 0;
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart == &huart2) {
        tx_busy = 0;
    }
}

There is a trap here that the shape of the code hides. The DMA reads from your buffer while the call has already returned, so the buffer must stay valid and unchanged until the completion callback runs. Passing a local array that goes out of scope when the function returns is a bug that produces garbled output and no error, since the stack space is overwritten while the stream is still reading it. Use a static or global buffer, or one allocated for the transfer and freed in the callback. The UART transmit queue post builds that pattern into a ring buffer.

For receiving data of unknown length, the HAL offers a call that runs a circular DMA and reports whenever the line goes idle, which suits command-and-response protocols:

uart_rx.cc
uint8_t rx_buf[128];

void uart_rx_start(void) {
    HAL_UARTEx_ReceiveToIdle_DMA(&huart2, rx_buf, sizeof rx_buf);
}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t size) {
    // 'size' bytes have arrived in rx_buf since the last event
    process_bytes(rx_buf, size);
    HAL_UARTEx_ReceiveToIdle_DMA(huart, rx_buf, sizeof rx_buf);
}

The callback receives how many bytes have been received so far, and it fires when the line has been quiet for one character time, which marks the end of a burst. Restart the reception in the callback, as shown, or the stream stops after the first burst in normal mode.

The events a DMA channel reports

Three conditions matter on nearly every controller, and each has its own flag.

EventMeaningTypical use
Half transferHalf the count has been movedProcess the first half of a circular buffer
Transfer completeThe count reached zeroRelease a buffer, start the next transfer
Transfer errorA bus error, or a bad address or alignmentStop and log; the stream disables itself

On STM32 the flags are also available in the status registers, and the HAL handler clears them before it calls your callback. If you write a handler without the HAL, you must clear each flag in the interrupt clear register yourself, or the interrupt fires again immediately. Some controllers add events for FIFO errors and for direct-mode errors; they are rare and mean the FIFO threshold and burst settings do not match the data widths.

Enable the error interrupt in any firmware you will ship. A transfer that silently stops is among the hardest bugs to find, because the rest of the program looks healthy.

Request routing: fixed tables and DMAMUX

Where a request line goes is a fixed property of the silicon on the STM32F4. A peripheral's request reaches specific streams, and each stream serves different peripherals depending on its channel selection. A few entries from the F407 table:

Peripheral requestController, stream, channel
ADC1DMA2, stream 0 or 4, channel 0
USART2_RXDMA1, stream 5, channel 4
USART2_TXDMA1, stream 6, channel 4
SPI1_RXDMA2, stream 0 or 2, channel 3
SPI1_TXDMA2, stream 3 or 5, channel 3
DAC1DMA1, stream 5, channel 7

Two of those peripherals want stream 5 on DMA1, which is a conflict: if you use USART2 receive and DAC1 at the same time, one of them has to move, and for the DAC there is no alternative stream. This is the sort of constraint you check at the start of a project, not at the end.

Newer families such as the STM32G4, L4+ and H7 add a request multiplexer, DMAMUX, between the peripherals and the channels. Any request can be routed to any channel, so conflicts disappear. In the HAL you select the request with hdma.Init.Request, for example DMA_REQUEST_ADC1, and pick any free channel. The DMAMUX post covers the routing, including request generators and synchronization signals that gate a channel.

The RP2040 takes a middle path. Every DMA channel can serve any request, selected with the transfer request signal field, DREQ. The SDK exposes constants such as DREQ_UART0_TX and helpers like pio_get_dreq, and channel_config_set_dreq(&cfg, DREQ_UART0_TX) makes the channel pace itself on the UART's transmit FIFO.

uart_dma_pico.cc
dma_channel_config c = dma_channel_get_default_config(ch);
channel_config_set_transfer_data_size(&c, DMA_SIZE_8);
channel_config_set_read_increment(&c, true);
channel_config_set_write_increment(&c, false);
channel_config_set_dreq(&c, uart_get_dreq(uart0, true));
dma_channel_configure(ch, &c, &uart_get_hw(uart0)->dr, message, sizeof message, true);

The write address is the UART's data register, with write increment off, and the read side walks through the message. The request signal throttles the channel so it only writes when the UART's transmit FIFO has room, which is the property that makes peripheral-triggered DMA safe against overrun.

Which memory the DMA can reach

A DMA controller is a bus master with its own connections to the memories, and not every memory is reachable from every controller. On the STM32F407, the 64 KB of core-coupled memory, CCM RAM at address 0x10000000, is connected only to the CPU's data bus. A DMA stream pointed at it fails with a transfer error, or, if the error interrupt is off, does nothing. The linker script decides where variables go, so a buffer that lands in CCM because it was placed in the default .data of a project that puts everything there breaks DMA with no visible link between cause and symptom. Place DMA buffers explicitly in the SRAM sections that the controller can reach.

Four other memory rules apply across chips:

  • Alignment. A word transfer to an address that is not word-aligned raises an error on most controllers, and on a few it silently corrupts. Declare DMA buffers with __attribute__((aligned(4))), or larger, to match the widest unit.

  • Lifetime. A buffer must outlive the transfer, as the UART example showed.

  • Cache. On parts with a data cache between the CPU and memory, such as the Cortex-M7, the CPU may read stale data that the DMA has just changed, or the DMA may read memory that the CPU has written only into its cache. The remedy is to clean and invalidate cache lines around transfers or to place buffers in non-cacheable memory. The cache post explains the mechanics and the maintenance post shows the calls.

  • Capability. On the ESP32, DMA needs memory from a specific region, and heap_caps_malloc with MALLOC_CAP_DMA hands it out. A buffer in the wrong region gives an error at the driver call. See the ESP32 DMA memory post.

Chaining channels and double buffering

A single transfer ends. Real systems often need transfers that follow each other with no gap. The RP2040 provides chaining directly: a channel can be configured to start another when it finishes. Two channels chained to each other make a ping-pong, with one buffer filling while the other is processed.

pingpong.cc
#include "hardware/dma.h"
#include "hardware/irq.h"

#define N 256
static uint16_t buf_a[N], buf_b[N];
static int ch_a, ch_b;

static void dma_handler(void) {
    if (dma_channel_get_irq0_status(ch_a)) {
        dma_channel_acknowledge_irq0(ch_a);
        dma_channel_set_write_addr(ch_a, buf_a, false);   // re-arm for next time
        // buf_a is complete and stable here
    }
    if (dma_channel_get_irq0_status(ch_b)) {
        dma_channel_acknowledge_irq0(ch_b);
        dma_channel_set_write_addr(ch_b, buf_b, false);
        // buf_b is complete and stable here
    }
}

void pingpong_start(void) {
    ch_a = dma_claim_unused_channel(true);
    ch_b = dma_claim_unused_channel(true);

    dma_channel_config ca = dma_channel_get_default_config(ch_a);
    channel_config_set_transfer_data_size(&ca, DMA_SIZE_16);
    channel_config_set_read_increment(&ca, false);
    channel_config_set_write_increment(&ca, true);
    channel_config_set_dreq(&ca, DREQ_ADC);
    channel_config_set_chain_to(&ca, ch_b);

    dma_channel_config cb = ca;
    channel_config_set_chain_to(&cb, ch_a);

    dma_channel_configure(ch_a, &ca, buf_a, &adc_hw->fifo, N, false);
    dma_channel_configure(ch_b, &cb, buf_b, &adc_hw->fifo, N, false);

    dma_channel_set_irq0_enabled(ch_a, true);
    dma_channel_set_irq0_enabled(ch_b, true);
    irq_set_exclusive_handler(DMA_IRQ_0, dma_handler);
    irq_set_enabled(DMA_IRQ_0, true);

    dma_channel_start(ch_a);
}

When channel A fills buf_a it triggers channel B, which fills buf_b and triggers A, and so on forever. The interrupt handler's one job is to re-arm the finished channel's write address, since the address advanced to the end of the buffer during the transfer. The finished buffer is then free for the CPU to read for as long as the other channel takes to fill, which is N conversions of the ADC. The RP2040 chaining post shows the full ADC setup this fragment assumes, including the ADC FIFO configuration.

On STM32F4, the double-buffer mode of a stream gives the same ping-pong inside one stream, with two memory addresses that the stream alternates between, as covered in the double-buffer post.

The same idea on other chips

DMA looks different on every vendor's part, and the vocabulary is the obstacle more than the hardware. Mapping the terms once saves a lot of reading.

IdeaSTM32RP2040ESP32nRF52
Transfer engineStream or channel in DMA1, DMA2One of 12 channelsGeneral DMA channels, driven by driversEasyDMA inside each peripheral
TriggerRequest line, optionally through DMAMUXDREQ signalPeripheral-specific, set by the driverThe peripheral itself
CountNDTRTRANS_COUNTDescriptor lengthMAXCNT
Continuous modeCircular modeChaining or ring wrapLinked descriptors that loopRestart with a task or a shortcut
ChainingDouble-buffer mode, linked-list mode on newer partsCHAIN_TO fieldLinked-list descriptorsShortcuts between events and tasks

Two of those columns deserve a paragraph each, because they break the "one controller, many channels" model that the STM32 and RP2040 share.

On the nRF52 series there is no separate controller. Every peripheral that moves data, the UART, SPI, I2S and ADC, contains its own small DMA engine called EasyDMA, with a pointer register and a maximum-count register. You write the buffer's address and its length into the peripheral and trigger it, and the peripheral reads or writes the memory itself. The practical consequences are that there is no stream or channel to choose and no request table to consult, and that the buffer must live in RAM, never in flash, because EasyDMA cannot read the flash controller on those parts. A constant string that the linker placed in flash has to be copied to RAM before it can be sent.

On the ESP32, the DMA engine exists, but the SDK hides it behind the peripheral drivers. When you start an SPI master transaction with a buffer larger than the hardware FIFO, the driver builds a linked list of descriptors, each pointing at a chunk of the buffer, and the DMA engine walks the list. You never configure a channel yourself. What you do own is the buffer, and the driver requires it to come from DMA-capable memory, which the heap allocator provides when you ask for it with the right capability flag. The ESP32 DMA memory post shows the allocator calls and what a buffer in the wrong region does.

Descriptors and scatter-gather

A single address, count and direction cover a flat buffer. Real data is often not flat: a network packet is a header here and a payload there, a display frame is a set of rows with a stride between them, an audio ring buffer wraps in the middle of a transfer. Handling those with plain DMA takes one transfer per piece and an interrupt after each to start the next, which gives back the CPU time DMA was meant to save.

Scatter-gather solves it with a list of descriptors in memory. Each descriptor holds a source, a destination, a length and a pointer to the next descriptor, and the controller follows the pointers on its own. You build the list once, point the controller at its head and start. Controllers differ in how they spell this. The ESP32 engine uses linked descriptors as its native format. Newer STM32 general-purpose DMA controllers add a linked-list mode in which each node carries a full channel configuration. The RP2040 does not have a descriptor list, and approximates it with channel chaining and control blocks: a "control" channel writes a new configuration into a data channel's registers through an alias address, then triggers it, which gives the same effect for a fixed sequence of transfers.

The reason to know it exists is that a stream broken into pieces by software is a sign that the controller can probably do the whole thing in hardware. Before you add a second interrupt to restart a transfer, look at the reference manual's section on linked lists or chaining.

Worked sizing: capturing audio

A concrete case ties the numbers together. Capture stereo audio at 48,000 frames per second with 16-bit samples, delivered by an I2S peripheral. A frame is two samples of two bytes, 4 bytes, so the stream is:

Text
48,000 frames/s * 4 bytes = 192,000 bytes/s

Choose a half buffer of 1,024 frames, 4,096 bytes. The DMA fills it in 1,024 / 48,000 seconds:

Text
half-buffer period = 1,024 / 48,000 = 21.3 ms
interrupts per second = 2 per full buffer = about 46.9
buffer memory = 2 * 4,096 = 8,192 bytes

At 47 interrupts per second the CPU spends almost nothing on transfers, and the processing code has 21.3 milliseconds to encode, filter or forward each half. A half buffer of 128 frames would give 2.7 milliseconds and 375 interrupts per second, which is still modest but leaves less slack when other interrupts arrive. The trade is plain: bigger buffers use more RAM and add latency, since the first sample of a half waits for the whole half to fill, but they buy deadline slack and fewer interrupts. For audio that is played back in real time, latency adds up across stages, so choose the smallest buffer whose deadline your processing meets with margin, not the largest your RAM allows.

Stopping and recovering a transfer

Starting a stream is half the work. Firmware also has to stop one, on shutdown, on an error or when switching modes, and the order matters. Stopping the DMA stream while the peripheral keeps raising requests leaves the peripheral waiting for a transfer that will never come, and restarting later can deliver a stale request. The safe order is to stop the source of requests first, then abort the stream, then clear the flags and start again.

restart.cc
void adc_stream_restart(void) {
    HAL_ADC_Stop_DMA(&hadc1);                 // stops the ADC requests and the stream
    __HAL_DMA_CLEAR_FLAG(&hdma_adc1, DMA_FLAG_TCIF0_4 | DMA_FLAG_HTIF0_4 |
                                      DMA_FLAG_TEIF0_4 | DMA_FLAG_DMEIF0_4 |
                                      DMA_FLAG_FEIF0_4);
    first_half_ready = second_half_ready = 0;
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buf, BUF_LEN);
}

The HAL's stop function aborts the stream and disables the ADC's DMA requests together, which is the correct order. If you write the same thing with registers, clear the peripheral's DMA enable bit, then clear the stream's enable bit and wait for the hardware to confirm it has stopped, because a stream does not stop instantly: it finishes the unit it has in flight, and the enable bit reads back as 1 until it does. Reconfiguring a stream whose enable bit is still set is ignored by the hardware, which is a quiet reason for a restart that does not take.

A transfer error should also lead somewhere deliberate. The cheapest policy is to stop the stream, count the error, restart it and carry on, and to raise a fault flag if errors repeat within a short window. Silent restarts hide a wiring or configuration problem, so log them.

Priorities, arbitration and throughput

A DMA controller shares the buses with the CPU and with the other streams. Two layers of arbitration apply, and neither shows up in a first example.

Between streams of one controller, each stream has a priority level. On the STM32F4 there are four, low, medium, high and very high, and when two streams request at once the higher level wins. Equal levels are resolved by stream number, with the lower number first. A stream that is always losing is starved, which looks like an ADC buffer filling slower than expected. Give the time-critical streams a higher priority than the bulk ones: the ADC and the audio stream above a memory-to-memory copy.

Between the controller and the CPU, the bus matrix arbitrates in round-robin fashion for each memory or peripheral port. If the CPU and a DMA stream hit the same SRAM block at the same time, one waits a cycle. For most firmware the effect is invisible, but a tight CPU loop reading from the same memory the DMA is writing can run measurably slower while a transfer is active. Spread the buffers across separate SRAM blocks when a profile shows the contention.

The FIFO and burst settings on the F4 streams exist to use the bus more efficiently. A FIFO collects several units and moves them in one burst, which reduces the number of bus accesses and suits memory-to-memory and fast peripheral streams. The cost is added latency, since a unit waits in the FIFO until the burst is complete, and constraints on the combination of widths and burst sizes. The arbitration post measures when each setting matters. For a first design, leave the FIFO in direct mode, a burst of one, and let the defaults carry you.

Sizing buffers and deadlines

Every streaming design has a deadline, and it comes from the buffer size and the sample rate. If the half buffer holds H samples and the stream runs at fs samples per second, the CPU has H / fs seconds to finish with a half before the DMA overwrites it. The arithmetic for a few common rates with a 128-sample half buffer:

Sample rateHalf-buffer periodMemory for a 16-bit double buffer
8,000 samples/s16 ms512 bytes
20,000 samples/s6.4 ms512 bytes
100,000 samples/s1.28 ms512 bytes

The memory is the same because the buffer size, not the rate, determines it, while the deadline shrinks as the rate rises. At 100 kilosamples per second the CPU has about 1.3 milliseconds to process 128 samples, which is plenty for a simple filter and not enough for a large transform. If your processing is slower than the deadline, enlarge the buffer: doubling H doubles the deadline and the memory. It does not change the average CPU load, only how bursty it is.

Add a guard against a missed deadline. Count the half-transfer and complete events in the interrupt, count the halves the main loop has processed, and flag a fault when the difference exceeds one. A silent overrun produces corrupted data without a visible error, and a counter turns it into something you can log.

When something does not work

Most DMA failures come from a short list of causes. Walk it before reaching for a logic analyzer.

SymptomLikely cause
Nothing transfers, no errorWrong stream and channel for the peripheral request; DMA clock not enabled; the peripheral's own DMA enable bit not set
Transfers once, then stopsNormal mode where circular was needed, or the callback does not re-arm the transfer
Every unit lands in the same slotMemory increment disabled
Data shifted or half-garbledMismatched data widths between peripheral and memory sides
Transfer error flagBuffer in memory the DMA cannot reach, or a misaligned address
Values look stale on Cortex-M7Cache not cleaned before transmit or not invalidated after receive
Transmitted bytes are wrongBuffer on the stack or modified before the transfer completed
Throughput lower than expectedPriority too low, FIFO not used for a burst-friendly stream, or bus contention with the CPU
First sample is odd after startThe peripheral raised a request before the stream was enabled; start the stream first

The last row bites on ADC streaming: start the DMA, then enable the trigger that starts conversions, in that order. The reverse leaves one conversion pending with nowhere to go, and it is delivered as a stale value or flagged as an overrun.

When DMA is not the answer

DMA has costs: setup code, a buffer to manage, a lifetime rule and an interrupt to get right. A few cases do better without it.

Small transfers at low rates. A temperature read once a second over I2C needs three bytes, and an interrupt-driven or even blocking read is simpler than a DMA channel for them.

Parts without a DMA controller. Small AVR and many entry-level Cortex-M0 parts have none, and the peripheral FIFO plus a short interrupt is the available option. Some of those peripherals have deep FIFOs that reduce interrupts without DMA.

A transfer whose result you need immediately. DMA is asynchronous, and a design that sets up a transfer and then blocks waiting for it has paid the setup cost for nothing.

Hard real-time loops sensitive to bus contention. A DMA stream can add wait cycles to CPU accesses. In a hard real-time control loop, measure the worst case with the DMA running, not the average.

Safety-critical data paths. DMA bypasses the CPU's memory protection on parts without a memory protection unit for the controller. A wrong address can overwrite any memory the bus allows, including code or configuration. Parts with an IOMMU or a DMA-aware protection scheme exist, and a safety design should use one or validate addresses before configuring a stream.

Checking a DMA design before you trust it

A DMA stream that works on the bench for ten seconds can still be wrong, and the faults it hides are the intermittent kind. Three checks catch most of them early.

First, fill the destination buffer with a known pattern before the transfer, such as 0xA5A5A5A5, and inspect it afterwards. Any slot that still holds the pattern was never written, which finds count errors, increment errors and alignment errors at once. A buffer that was zeroed first can hide a transfer that did nothing, because zero is also a plausible sample.

Second, put a sentinel word just past the end of the buffer. A DMA that writes one unit too many, or one that runs in circular mode with the wrong count, overwrites it, and a check in the main loop shows the corruption long before it reaches something visible.

Third, run the stream under load. Start a long memory copy on another stream, enable the display refresh and let the CPU run its heaviest code while you watch the missed-deadline counter. Contention for the bus and a late interrupt show up only when everything runs at once, and a design that passes alone and fails under load has an arbitration or priority problem, not a logic bug.

Where to go from here

If you have a streaming peripheral, the next steps are the half-transfer buffer for continuous data and the transmit queue for output. If your part has a data cache, read the cache posts before the first DMA buffer goes into production, since the symptoms of a coherency bug are indistinguishable from random noise. If you are moving data at a high rate, the arbitration and FIFO post tells you what to tune. And when DMA works on one chip, the same model reads straight across to the next: find the source and destination address registers, the count, the increments, the request source and the interrupt flags, and you have mapped the new controller to what you already know.

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.