What is DMA and how is it configured?
Short answer: A Direct Memory Access controller transfers data between peripherals and memory (or memory and memory) without the CPU copying each word. You configure the source and destination addresses, the number of items and their width, whether each address increments, the direction, the trigger (which peripheral request starts each transfer), priority, and normal or circular mode; interrupts signal half-transfer, transfer-complete and errors.
Typical channel configuration (UART receive into a buffer)
| Setting | Value |
|---|---|
| Source | &USART2->DR (peripheral, fixed address: no increment) |
| Destination | rx_buf (memory, increment after each item) |
| Item size | 8 bits both sides |
| Count | sizeof rx_buf |
| Request/stream | USART2_RX (via the DMA request mux on newer parts) |
| Mode | circular |
| Interrupts | half-transfer, transfer-complete, transfer-error |
Then enable the peripheral's DMA request (USART2->CR3 |= USART_CR3_DMAR) and the stream.
Circular mode + half/complete interrupts = double buffering: while DMA fills the second half of the buffer, the CPU processes the first half, and vice versa. For variable-length messages over UART, combine circular DMA with the IDLE line interrupt and read the DMA's remaining-count register (NDTR) to know how many bytes arrived.
Other features
- Memory-to-memory transfers (fast
memcpythat frees the CPU). - Scatter-gather / linked-list descriptors (on more advanced controllers and on application processors): a chain of transfers to non-contiguous buffers without CPU intervention.
- FIFO and burst modes to use the bus efficiently and pack bytes into words.
- Priority levels when several streams compete.
Common pitfalls
- Buffer lifetime: never use a local (stack) buffer for a DMA transfer that outlives the function.
- Cache coherency on Cortex-M7/A (clean/invalidate, alignment).
- Bus access restrictions: some DMA controllers cannot reach certain memories (e.g. DTCM on STM32H7) — the transfer fails silently or with an error flag.
- Volatile: the CPU reading a buffer that DMA writes must not be optimised into reading stale values; use
volatileaccess or a barrier after the completion interrupt. - Error handling: check transfer-error flags (bus errors from bad addresses).