📚 CMPE2250: Lesson — Direct Memory Access (DMA) & DMAMUX Driver Development
Course Material & Lab Assignment Guide
Target Architecture: STM32G0 Series (ARM Cortex-M0+)
1️⃣ Objectives & Overview
In high-throughput embedded systems, servicing communication lines (such as UART, SPI, or I2C) byte-by-byte using standard interrupt service routines (ISRs) imposes significant CPU overhead. Direct Memory Access (DMA) offloads bulk data transfers between peripherals and memory (or memory to memory) without CPU intervention.
In this activity, you will:
- Understand the clock distribution requirements (RCC) for bus masters.
- Configure the DMAMUX (DMA Request Multiplexer) crossbar router.
- Design and implement a reusable register-level DMA driver library (
dma.handdma.c). - Validate your driver using peripheral-to-memory data transfers paired with UART IDLE line detection.
2️⃣ Hardware Architecture & Bus Interconnect
2.1 The DMA Controller and DMAMUX
In the STM32G0 family, DMA channels are decoupled from fixed peripheral lines through the DMAMUX:
+------------------+ +-------------------+ +---------------+ +----------------+
| Peripherals | | DMAMUX | | DMA1 / DMA2 | | Bus Matrix |
| (USART, SPI, etc)| ----> | Channel Routing | ----> | Channels 1..N | ----> | SRAM & |
| Hardware Triggers| | (Table 55 RM0444) | | (CCR, CNDTR) | | Periph Spaces |
+------------------+ +-------------------+ +---------------+ +----------------+
- DMAMUX Router: Directs hardware transfer trigger requests from any peripheral trigger output to any available DMA channel.
- DMA Controller: Orchestrates the actual bus mastering, auto-incrementing memory pointers, counting transfers down to 0, and triggering interrupts upon completion or errors.
3️⃣ Peripheral Clock Setup (RCC Prerequisites)
Important: By architectural convention, the DMA library functions operate only on the channel registers (
DMA_Channel_TypeDef) and expect the system clocks to be enabled prior to initialization.
Before any DMA channel or DMAMUX channel register can retain values, its peripheral clock must be activated via the RCC (Reset and Clock Control) registers.
3.1 Enabling DMA and DMAMUX Clocks in main()
Refer to the RCC AHB Peripheral Clock Enable Register (RCC->AHBENR):
- DMA1 / DMA2 Clock Enable: Find and set the corresponding enable bits (
RCC_AHBENR_DMA1EN, andRCC_AHBENR_DMA2ENif present). - DMAMUX Clock Enable: Set the DMAMUX enable bit (
RCC_AHBENR_DMAMUX1EN). - Synchronization Delay: Perform a dummy read or add a brief delay immediately after setting peripheral clock bits to allow the clock distribution to settle before accessing peripheral registers.
4️⃣ DMAMUX Routing Configuration
The DMAMUX assigns a peripheral hardware trigger ID to a given DMA channel.
Each DMAMUX channel configuration register (DMAMUX1_Channelx->CCR) corresponds directly to a DMA channel:
DMAMUX1_Channel0routes requests to DMA1 Channel 1.DMAMUX1_Channel1routes requests to DMA1 Channel 2, and so on.
4.1 Configuration Procedure
- Locate the Request ID in your provided header:
dmamux.h(mapped from RM0444 Table 55).- Example: For USART2 RX, the ID is
DMAMUX_REQ_USART2_RX(value52).
- Example: For USART2 RX, the ID is
- Write the ID into the
DMAREQ_ID[6:0]bitfield inDMAMUX1_Channelx->CCR: \(\text{DMAMUX1\_Channelx->CCR} = \text{Request\_ID} \ \& \ \text{DMAMUX\_CxCR\_DMAREQ\_ID}\) - Verify that synchronization and trigger generator modes remain disabled (default
0) for basic peripheral-driven requests.
5️⃣ DMA Register Model
Each DMA channel is controlled through four core 32-bit registers encapsulated in CMSIS by DMA_Channel_TypeDef:
| Register | Name | Purpose | Configuration Condition |
|---|---|---|---|
CCR |
Channel Configuration Register | Controls enable, directions, increment modes, circular mode, priorities, and interrupt enables. | Most bits writeable only when EN = 0. |
CNDTR |
Number of Data to Transfer | Holds the transfer count ($0$ to $65535$). Decrements after each transfer. | Must only be modified when EN = 0. |
CPAR |
Peripheral Address Register | Base address of the peripheral register (e.g., &(USART2->RDR)). |
Writeable when EN = 0. |
CMAR |
Memory Address Register | Target/source address of the data buffer in SRAM. | Writeable when EN = 0. |
6️⃣ Driver Library Design Guide
Your assignment is to implement dma.c according to the definitions in dma.h.
6.1 Header Definitions (dma.h)
Your header exposes the transfer mode enum, the interrupt enable bitmasks, and function prototypes:
typedef enum DMAChannelMode__ {
DMA_MemToMem,
DMA_PerToMem,
DMA_MemToPer,
DMA_PerToPer,
} DMAChannelMode;
typedef enum DMA_IE__ {
DMA_EIE = (1 << DMA_CCR_TEIE_Pos), // Transfer Error Interrupt Enable
DMA_HTIE = (1 << DMA_CCR_HTIE_Pos), // Half Transfer Interrupt Enable
DMA_TCIE = (1 << DMA_CCR_TCIE_Pos), // Transfer Complete Interrupt Enable
} DMA_IE;
6.2 Implementation Steps (dma.c)
Step 1: Channel Initialization (DMA_Init)
- Signature:
void DMA_Init(DMA_Channel_TypeDef *pChannel, DMAChannelMode mode, uint8_t* memAddr, uint32_t perAddr); - Requirements & Logic:
- Enforce Safe State: Clear the
DMA_CCR_ENbit inpChannel->CCR. A channel cannot be modified while enabled. - Set Addresses: Load
memAddrintoCMARandperAddrintoCPAR(use your helper functions). - Mode Resolution (
switch(mode)):DMA_MemToMem:- Enable Memory-to-Memory mode (
DMA_CCR_MEM2MEM). - Clear Direction (
DMA_CCR_DIR = 0). - Enable Memory Increment (
DMA_CCR_MINC) to advance the destination buffer. - Enable Peripheral Increment (
DMA_CCR_PINC) to advance the source buffer.
- Enable Memory-to-Memory mode (
DMA_PerToMem(e.g., UART Reception):- Disable Memory-to-Memory (
MEM2MEM = 0). - Clear Direction (
DIR = 0$\rightarrow$ read from peripheral into memory). - Enable Memory Increment (
MINC = 1). - Disable Peripheral Increment (
PINC = 0), since the peripheral register is a fixed single address.
- Disable Memory-to-Memory (
DMA_MemToPer(e.g., UART Transmission):- Disable Memory-to-Memory (
MEM2MEM = 0). - Set Direction (
DIR = 1$\rightarrow$ read from memory into peripheral). - Enable Memory Increment (
MINC = 1). - Disable Peripheral Increment (
PINC = 0).
- Disable Memory-to-Memory (
DMA_PerToPer:- Disable Memory-to-Memory (
MEM2MEM = 0). - Clear Direction (
DIR = 0). - Disable both pointer increments (
MINC = 0,PINC = 0).
- Disable Memory-to-Memory (
- Baseline Interrupt Flags: Enable Transfer Complete (
DMA_CCR_TCIE) and Transfer Error (DMA_CCR_TEIE) inCCR.
- Enforce Safe State: Clear the
Step 2: Address Setters (DMA_SetMemoryAddress, DMA_SetPerAddress)
- Write helper functions to encapsulate hardware register layout:
- Cast the pointer
uint8_t* memAddrtouint32_tand assign it topChannel->CMAR. - Assign the
uint32_t perAddrtopChannel->CPAR.
- Cast the pointer
Step 3: Transfer Control (DMA_SetEnable, DMA_StartTransfer)
DMA_SetEnable(DMA_Channel_TypeDef *pChannel, uint8_t en):- Set or clear
DMA_CCR_ENusing standard bitwise operators (|=or&= ~).
- Set or clear
DMA_StartTransfer(DMA_Channel_TypeDef *pChannel, uint16_t size):- Any modification to
CNDTRwhileEN = 1is ignored by the hardware and risks undefined behavior. - Sequence:
- Disable channel via
DMA_SetEnable(pChannel, 0). - Write
sizeintopChannel->CNDTR. - Re-enable channel via
DMA_SetEnable(pChannel, 1).
- Disable channel via
- Any modification to
Step 4: Tracking Received Bytes (DMA_GetRcvdCount)
- Mathematical Basis:
CNDTRis initialized to the total buffer capacity and decrements by $1$ after every successfully transferred byte. \(\text{Bytes Received} = \text{Total Buffer Size} - \text{CNDTR}\) - Implementation Note: Ensure the calculation uses the full buffer allocation size passed into the function.
Step 5: NVIC & Channel Interrupt Configuration (DMA_InterruptEnable)
- Configure the channel’s interrupt mask:
- Apply the bitmask flag (
DMA_IE) directly topChannel->CCR. - Enable the corresponding channel interrupt vector in the Cortex-M NVIC using
NVIC_EnableIRQ(irqn).
- Apply the bitmask flag (
7️⃣ Laboratory Exercise: Peripheral-to-Memory UART with IDLE Line Detection
To verify your library, configure USART reception where packet sizes are variable and unknown in advance.
7.1 The Problem with Variable-Length Packets
If you configure a DMA channel to receive 64 bytes, but the sender only transmits a 12-byte command, the DMA will wait indefinitely for the remaining 52 bytes without firing the Transfer Complete (TC) interrupt.
7.2 The Solution: UART IDLE Line Detection
The STM32 UART hardware can detect when the receive line becomes idle (no RX traffic for more than one frame duration).
UART RX Line: ---[ Byte 1 ][ Byte 2 ][ Byte 3 ]---------------------> (IDLE detected!)
^
|-- Fires USART_ISR_IDLE Interrupt!
7.3 Integration Steps for Students
- Clock Setup:
- Enable clocks for GPIOA, USART2, DMA1, and DMAMUX1 in
RCC.
- Enable clocks for GPIOA, USART2, DMA1, and DMAMUX1 in
- DMAMUX Routing:
- Connect
DMAMUX_REQ_USART2_RXtoDMAMUX1_Channel0(which feedsDMA1_Channel1).
- Connect
- DMA Library Call:
- Call
DMA_Init()targetingDMA1_Channel1, setting mode toDMA_PerToMem, pointing to your global RX buffer, and passing the address ofUSART2->RDR. - Enable the DMA channel for a maximum expected buffer size (e.g., 64 bytes).
- Call
- USART Configuration:
- Enable USART DMA Reception by setting the
DMARbit inUSART2->CR3. - Enable the IDLE Line Interrupt by setting the
IDLEIEbit inUSART2->CR1. - Enable
USART2_IRQnin the NVIC.
- Enable USART DMA Reception by setting the
- Handling the Interrupt:
- In
USART2_IRQHandler():- Check if the
IDLEflag inUSART2->ISRis asserted. - Clear the flag by writing
USART_ICR_IDLECFtoUSART2->ICR. - Call your driver function: \(\text{count} = \text{DMA\_GetRcvdCount(DMA1\_Channel1, BUFFER\_SIZE)}\)
- Process the received payload up to
count. - Reset the transfer for the next packet by calling
DMA_StartTransfer(DMA1_Channel1, BUFFER_SIZE).
- Check if the
- In
8️⃣ Verification & Debugging Checklist
Before requesting sign-off or submitting your code, verify these common pitfalls in the IDE debugger:
- RCC Active: Inspect
RCC->AHBENRin the Peripherals View. Are theDMA1ENandDMAMUX1ENbits set to1? - Safe Configuration: Place a breakpoint inside
DMA_Init(). Confirm thatCCRhasEN = 0before any other bitfield changes. - Address Pointers: Check
CMARandCPAR. DoesCPARmatch the memory address of the peripheral data register (e.g.,0x40004424for USART2 RDR)? - DMAMUX Request Mapping: Check
DMAMUX1_Channel0->CCR. Does the lower byte match the ID defined indmamux.h? - Pointer Increment Flags: In Memory-to-Memory transfers, verify that both
MINCandPINCare active. In UART-to-Memory transfers, verify that onlyMINCis active. - Interrupt Acknowledgement: When writing an ISR, verify that the corresponding interrupt status flag in
DMA1->ISR(e.g.,CTCIFx) orUSARTx->ICRis cleared to prevent infinite interrupt loops.