Labs / MicroPython tutorials

19 DMA Direct Memory Access - Document Tutorial Draft

Author: Li Zisheng · Source: FreakStudio open documentation, v1.0.1 · License: CC BY 4.0

Contents

1. Hardware Explanation

1.1 Introduction to DMA

1.1.1 Introduction to DMA (Direct Memory Access)

In traditional data transmission modes, the CPU of a microcontroller unit (MCU) is responsible for reading data from a peripheral (such as I2C, UART, ADC, etc.) and storing it in memory, or reading data from memory and writing it to the peripheral. This approach requires the CPU to continuously process read and write operations, which easily leads to excessive CPU load and affects the overall performance of the system.

The introduction of DMA changed this situation. DMA, short for Direct Memory Access, is a technology that allows hardware subsystems to exchange data directly with memory without the intervention of the CPU (Central Processing Unit). DMA significantly improves system performance, especially in applications that require large volumes of data transmission, such as audio/video processing, network communication, and Data Acquisition.

19 DMA Direct Memory Access - Document Tutorial Draft
Using DMA (Direct Memory Access), data can be transferred directly between peripherals and memory without CPU involvement

Using DMA for data transmission enables automatic data transfer in the background, so the CPU does not need to participate in the specific data handling work, which frees up more CPU resources for executing other tasks; meanwhile, since the DMA controller directly exchanges data with the memory and devices, it can transmit data at a faster speed than that controlled by the CPU.

Compared with the method where the CPU reads data in the interrupt callback function after a peripheral generates an interrupt, DMA transfer can significantly reduce the number of interrupts related to data transmission that the CPU has to process, thereby lowering the interrupt overhead of the system.

1.1.2 Working Principle of DMA

The DMA controller can directly communicate with the system bus and is responsible for managing data transmission between devices and memory. It operates through the following steps:

19 DMA Direct Memory Access - Document Tutorial Draft
Simplified diagram of the DMA data transfer flow
  1. DMA transfer request: Before using DMA, we first need to configure information such as the source address, destination address and data transfer size for DMA data transmission. When a peripheral (such as a UART or ADC) needs to perform data transmission, it sends a transfer request to the DMA controller. At this point, the CPU can configure and initiate the DMA transfer, but the actual data operation of the transfer is taken over by the DMA controller, which temporarily seizes control of the system bus;
  2. DMA transfer: The DMA controller directly accesses memory via the system bus to move data from a source address (e. g., a device) to a destination address (e. g., memory), or from memory to a device. This process does not require CPU intervention; the DMA controller can complete the transfer operation in the background, and data transmission is carried out through DMA channels;It should be noted that the DMA channels responsible for data transmission rely on the system bus;
  3. Interrupt Notification: When the DMA transfer is completed, the DMA controller will send an interrupt signal to the CPU to notify that the transfer has finished, and meanwhile hand over the system bus controller to the CPU. At this point, the CPU can continue to process data-related tasks without spending time and resources on data transfer.

It can be seen that the DMA controller and DMA channels enable devices to transmit data without overloading the CPU; without DMA channels, the CPU would use the system bus to send instructions and data to the peripheral bus, which then routes them to the target peripheral device, before copying each piece of data into the array designated for data storage within that target device. Using the peripheral bus for read/write operations would occupy the CPU, preventing it from performing any other tasks until the operation is completed.

Here, the CPU, DMA, and other peripherals all share the same system bus. If the CPU is using the bus to perform a memory access operation while the DMA also needs to transfer data to or read data from memory via the bus, a contention for the bus will arise between the two parties. In this case, there is an arbitration mechanism in the system to determine the right to use the bus and which party will take control of it; the arbiter will decide whether the CPU or the DMA should have priority in using the bus based on factors such as task priority, urgency, and system status.

However, there are also some issues encountered when using DMA for data transmission, for instance the cache coherence problem: when an MCU is equipped with a cache mechanism (such as the F7 series, U5 series and H7 series of STM32 microcontrollers), the CPU usually accesses the cache first instead of directly accessing the RAM memory to improve data access speed when reading or writing data; however, the DMA controller communicates directly with the RAM, bypassing the CPU cache.

19 DMA Direct Memory Access - Document Tutorial Draft
Diagram of the DMA cache coherency problem

This will lead to the following issues:

To avoid or solve the cache coherence problem in MCUs, the following methods can be used:

1.1.3 Types of DMA

According to the direction and mode of data transmission, DMA can be divided into the following types:

19 DMA Direct Memory Access - Document Tutorial Draft

1.1.4 DMA Transfer Modes

DMA controllers typically support multiple transfer modes; the following are several common ones:

1.1.5 Structure of DMA

For the DMA unit of an MCU, it can generally be divided into the following parts:

19 DMA Direct Memory Access - Document Tutorial Draft
Basic structure of the DMA unit in an MCU

1.2 DMA on Raspberry Pi Pico

1.2.1 Introduction to the DMA Unit on Raspberry Pi Pico

The DMA controller of the RP2040 features independent read and write master connections, which are respectively connected to the chip's bus architecture, enabling the DMA to perform parallel read and write operations. The specific architectural features are as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

Each DMA channel has its own control and status registers, through which software can configure the channel, including the following parameters:

19 DMA Direct Memory Access - Document Tutorial Draft
The CHAIN_TO bits are in the DMA channel's trigger control register

1.2.2 DMA Channel Configuration

Each DMA channel has four main Control and Status Registers (CSRs) for managing the data transfer process:

19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft

1.2.2.1 Read Address and Write Address Registers

READ_ADDR and WRITE_ADDR are registers used to store the memory address from which the DMA channel will read data or to which it will write data next time. These registers are automatically updated after each read or write operation, and will increment according to the transfer size setting configured in the CTRL register.

19 DMA Direct Memory Access - Document Tutorial Draft
The automatic read/write address update function can be enabled or disabled by configuring the INCR_WRITE and INCR_READ bits of the CTRL register

Specifically, the increment step size can be 1,2, or 4 bytes, depending on the configured transfer size. It should be noted that the READ_ADDR register and the WRITE_ADDR register must always be aligned to the current transfer size (the size specified in CTRL.DATA_SIZE): if the transfer size is byte (1 byte), halfword (2 bytes), or word (4 bytes), the corresponding address must be aligned to a 1-, 2-, or 4-byte boundary.

19 DMA Direct Memory Access - Document Tutorial Draft
The data transfer size can be configured through the DATA_SIZE bits of the CTRL register

Typically, whenever a new transmission sequence commences, the software needs to reprogram these registers to set a new start address. However, there are also scenarios where address increment is not required:

At this point, the DMA will use the current value as the starting address for the next transfer.

1.2.2.2 Transmission Count Register

TRANS_COUNT The register is responsible for managing the remaining number of transfers in the current transfer sequence, and determines the total number of transfers at the start of each transfer:

19 DMA Direct Memory Access - Document Tutorial Draft
The Read bits in the DBG_TCR register can be used to read the value of the DREQ counter

Here, it should be noted that TRANS_COUNT indicates the number of transmissions to be performed, and the total number of bytes to be transmitted is determined by both TRANS_COUNT and the data size per transmission (defined by the CTRL.DATA_SIZE register):

1.2.2.3 Control Trigger Register

The CTRL register is responsible for configuring and managing various behaviors of the DMA channel. Compared with other registers, the CTRL register contains more data bits, which are used to achieve more precise and detailed control over all aspects of the DMA channel, such as configuring the size of data transfer, the increment mode of read and write addresses, chained transfer, the selection of peripheral data request signals, as well as transfer status monitoring and error detection:

  1. Configure Transfer Data Size (CTRL.DATA_SIZE): This data bit is used to configure the data transfer size of this DMA channel, which can be set to 1 byte, 2 bytes, or 4 bytes; this data bit controls the size of each data read and write operation, and the size of the data block for reading is identical to that for writing.
  2. Configure the increment mode of read-write addresses:
    • CTRL.INCR_WRITE and CTRL.INCR_READ data bits control whether the write address (WRITE_ADDR) and read address (READ_ADDR) are incremented after each read/write operation; the increment magnitude shall be determined according to the configuration of CTRL.DATA_SIZE.
    • CTRL.RING_SEL and CTRL.RING_SIZE data bits are related to ring transmission:
      19 DMA Direct Memory Access - Document Tutorial Draft
      • Circular transmission means that the address pointer can wrap around to the start of the buffer at a predefined boundary, which is commonly used in data read and write operations related to the FIFO (First-In, First-Out) buffer of peripherals.
      • CTRL.RING_SEL Select whether to apply RING_SIZE to the read address or the write address
      • CTRL.RING_SIZE is used to set the size of the ring transmission data; the size of the ring buffer can be set to a value ranging from 2 to 32768 bytes. It should be noted that the value passed here corresponds to the number of data bits represented by the number of bytes in the buffer. Simply put, if ring_size is set to 8, the lowest 8 bits of the address register will change, which means the address will wrap around at a 256-byte boundary;the value of ring_size should be an integer between 0 and 31
  3. Configure Chained Transmission (CTRL.CHAIN_TO):
    19 DMA Direct Memory Access - Document Tutorial Draft
    • CTRL.CHAIN_TO The data bits are used to select another channel to be triggered when the current channel completes transmission: after a DMA channel finishes data transfer, it can automatically trigger the next DMA channel to continue the operation.
    • This method is called Channel Chaining, which is extremely useful in complex transmission scenarios, as it allows multiple DMA channels to execute sequentially without requiring CPU intervention.
    • If CTRL.CHAIN_TO is set to a certain channel number, the specified next channel will be automatically triggered when the current channel completes.
  4. Select Peripheral Data Request Signal (CTRL.TREQ_SEL):
    19 DMA Direct Memory Access - Document Tutorial Draft
    • CTRL.TREQ_SEL data bits are used to select the data request signal of a peripheral (DREQ) to control the transfer rate of the DMA channel.
    • DREQ signal is usually generated by a peripheral to request DMA to transfer data from the peripheral: for example, peripherals such as UART, SPI or I2C can generate such a request signal to control the DMA channel to transfer data at the appropriate timing so as to ensure data synchronization.
    • If no peripheral signal is selected, the DMA will not be limited by the data read/write speed of the peripheral, and will instead perform data transmission in accordance with the internal clock frequency of the DMA controller.
  5. Check whether the channel is idle (CTRL.BUSY):
    19 DMA Direct Memory Access - Document Tutorial Draft
    • CTRL.BUSY The data bit is used to indicate whether the DMA channel is currently busy performing a transfer operation:
      • When this data bit is 1, it indicates that the DMA channel is performing a transfer operation;
      • When this data bit is 0, it indicates that the channel is idle and can accept new transmission commands.
    • By checking CTRL.BUSY, the software can determine whether to submit a new transfer task or wait for the current task to complete
    • To terminate the transmission sequence in advance and clear the BUSY flag, you can use the CHAN_ABORT register
  6. Detection of bus errors (CTRL.AHB_ERROR, CTRL.READ_ERROR, CTRL.WRITE_ERROR): When any of the following error status bits is set, it indicates that a problem has occurred during the DMA transfer, which requires software-based debugging and error handling:
    19 DMA Direct Memory Access - Document Tutorial Draft
    • CTRL.AHB_ERROR The data bit indicates whether an AHB error occurred during the transmission of the DMA channel, which may be caused by accessing an invalid address or an unsupported peripheral address space.
    • CTRL.READ_ERROR The data bit indicates whether an error occurred during DMA read, such as accessing an invalid memory location or peripheral address.
    • CTRL.WRITE_ERROR The data bit indicates whether an error occurred during DMA write, such as writing to an invalid memory location or peripheral address.

1.2.3 Start the DMA channel for data transmission

There are three ways to start a DMA channel:

19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft

When starting a DMA channel, it should be noted that attempting to trigger a channel that is already running will have no effect.

1.2.3.1 Register Aliases and Trigger Mechanisms

Each DMA channel has four main Control and Status Registers (CSRs), which are as follows:

These registers have four distinct sets of aliases in memory; accessing each set of aliases addresses the same physical registers, albeit arranged in a different order.

19 DMA Direct Memory Access - Document Tutorial Draft
Control/status registers related to DMA channel 1 and their four aliases

The following table shows the address offsets and arrangement order of these register aliases:

19 DMA Direct Memory Access - Document Tutorial Draft

The last register of each alias (offset + 0xC) is the trigger register; writing to this register starts the DMA channel.

The main advantage of using aliases is that you can start a DMA channel by only writing to the key registers, without having to write to all configuration registers at once:

When performing chaining operations between DMA channels (i. e., starting another channel once one channel completes its task), aliasing enables transfer control to be implemented via a more compact control block list; with aliasing, there is no need to rewrite all registers — only those registers that have changed need to be written to:

The DMA channel cannot be started in the following cases:

1.2.3.2 Chained Triggering of DMA Channels

Chained triggering is a mechanism that allows one DMA channel to immediately trigger another channel upon completion of a transfer. In this way, the cooperative operation between two or more DMA channels can be realized. Common application scenarios include enabling one channel to immediately configure and start another channel after completing a transfer, and even reconfiguring the first channel through chained triggering.

Chain triggering is configured via the CTRL register of the DMA channel, specifically using the CHAIN_TO data bit field, which is a 4-bit value that specifies the target channel to be started after the current channel completes its transfer.

19 DMA Direct Memory Access - Document Tutorial Draft
CHAIN_TO bits in the CTRL register

Note that a channel cannot trigger itself; if CHAIN_TO is set to the index of the channel itself, no chain triggering will occur. Chain triggering behaves the same as a trigger operation from other sources (such as a trigger register), and it will cause the target channel's transfer counter (TRANS_COUNT) to be reloaded.

Chain triggering has a wide range of applications, and the following are two typical scenarios:

1.2.3.3 Empty Trigger and Chain Interruption

In DMA control, a Null Trigger refers to the operation of writing an all-zero value to the trigger register; when an all-zero value is written to the trigger register, the channel will not be activated. This operation is called a "null trigger" and it mainly serves two purposes:

In the CTRL register of the DMA channel, there is a data bit named IRQ_QUIET whose default value is 0, meaning that an interrupt will be generated each time a transmission sequence is completed; if it is set to 1, the channel will only generate an interrupt when receiving an empty trigger, and will not generate an interrupt at any other time:

19 DMA Direct Memory Access - Document Tutorial Draft
IRQ_QUIET bit of the CTRL register

1.2.4 DMA Data Request

In embedded systems, peripherals (such as UART, SPI, ADC, etc.) generate or consume data at their respective rates, which are usually not fixed; to ensure stable data transmission and avoid data loss or corruption, the DMA (Direct Memory Access) controller introduces a mechanism called DREQ (Data Request).

DREQ serves as the communication channel between the peripheral and DMA to regulate the transmission speed, so as to synchronize the data transfer of DMA with the rate of the peripheral. Its main function is to allow the peripheral to inform the DMA whether data transmission can be continued currently or should be suspended temporarily:

This mechanism can ensure that the peripheral will not lose data due to excessively fast transmission, or experience data accumulation due to excessively slow transmission.

In the CTRL.TREQ_SEL data bits of the DMA, you can configure how the DMA selects the source of the transfer request signal:

The following is the system DREQ table, which lists the DREQ channel numbers of various peripherals and their corresponding functions:

19 DMA Direct Memory Access - Document Tutorial Draft

Wherein:

1.2.5 DMA Channel Interrupt

Each DMA channel can generate an interrupt, and the interrupt request is triggered under the following circumstances:

19 DMA Direct Memory Access - Document Tutorial Draft
IRQ_QUIET bit of the CTRL register

The DMA of the RP2040 provides two system interrupts (IRQs), each with independent mask and status registers (such as INTE0 and INTE1), and interrupt requests can be routed to either of these two system interrupts. We can route interrupt requests from different channels to different system interrupts as needed; for example, certain channels with strict timing requirements can be configured to have higher priorities, and in multi-processor systems, interrupts from different channels can be independently routed to different processing cores to achieve more efficient interrupt handling.

We can check the INTR register to obtain the raw interrupt status of the DMA channels; the 16 data bits provide the raw interrupt status for DMA channels 0 through 15:

19 DMA Direct Memory Access - Document Tutorial Draft

We can check the masked interrupt status bits of each channel via the INTS register; to clear an interrupt, we can write a bit mask to INTS:

19 DMA Direct Memory Access - Document Tutorial Draft

We can mask interrupts by channel by configuring the INTE register, which allows users to select which channel interrupts are valid. Users can set or clear bits in these registers to enable or disable interrupt requests for specific channels:

19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft

We can forcibly trigger a DMA interrupt by configuring the INTF register:

19 DMA Direct Memory Access - Document Tutorial Draft

1.2.6 Other Features of DMA

1.2.6.1 Beat Timer

In the RP2040 microcontroller, the beat timer is used to control the rhythm of data transmission. It generates a data request (TREQ) at each clk_sys clock cycle without relying on the DREQ signal from an external peripheral. These timers use a fractional (X/Y) frequency divider to set the generation frequency of the requests.

19 DMA Direct Memory Access - Document Tutorial Draft

The maximum generation rate of each timer is one request per sys_clk cycle, and the generation rate of TREQ is ((X/Y) * sys_clk).

19 DMA Direct Memory Access - Document Tutorial Draft
1.2.6.2 CRC Check

The DMA function incorporates a CRC calculator, which can compute the checksum as data passes through the data FIFO of the DMA channel; this feature operates in a passive manner, meaning it does not modify the data, but merely monitors the data and calculates the checksum.

We can configure the specific parameters of CRC calculation through the SNIFF_CTRL register, and configure the SNIFF_DATA register to set the specific details of data processing.

19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft

Here, DMA supports check types such as CRC-32, CRC-16-CCITT, simple summation, and even parity.

1.2.6.3 Channel Abort

In the RP2040 microcontroller, DMA channels may enter an unrecoverable state. For example, when a channel is instructed to transfer more data than the peripheral can request, it will be unable to complete the transfer. In this case, simply clearing the CTRL.EN bit only pauses the channel and does not resolve the issue. To recover from such problems without having to perform a hard reset of the entire DMA block, the channel abort mechanism must be used.

We can configure the CHAN_ABORT register to force a channel to complete prematurely: writing 1 to the data bit corresponding to a specific channel will clear the channel's transfer counter and set the channel to an inactive state. This method allows forcing the channel into a safe state when an unrecoverable error is encountered, thereby avoiding the need to reset the entire DMA block.

19 DMA Direct Memory Access - Document Tutorial Draft

It should be noted here that due to the characteristics of the RP2040 chip, when aborting an ongoing DMA channel (that is, the channel is not suspended due to an inactive DREQ), it may cause the completion interrupt request (IRQ) to be triggered. Therefore, before performing the abort operation, the interrupt enable flag of the channel should be cleared first, and the interrupt should be checked and cleared after the abort operation.

When an abort operation is triggered, there may be ongoing bus transmissions on the channel. These transmissions cannot be revoked;the CTRL.BUSY flag will remain high until these transmissions complete and the channel reaches a safe state, a process that typically takes only a few clock cycles. The channel should not be restarted before its CTRL.BUSY flag goes low; starting a new transmission sequence while the old one is still in progress will result in unpredictable behavior.

1.2.6.4 Debugging

In the RP2040 microcontroller, each DMA channel is equipped with debug registers, which are used to display and debug the status of DMA operations; the debug registers include DBG_CTDREQ and DBG_TCR, which provide detailed information about the current status of the DMA channel and can be used to reset the DMA channel when necessary.

DBG_CTDREQ register is used to display the current value of the DREQ (transfer request) counter for the DMA channel:

19 DMA Direct Memory Access - Document Tutorial Draft

DBG_TCR register is used to display the value of the current transmission counter:

19 DMA Direct Memory Access - Document Tutorial Draft

2. Software Control Method

2.1 Constructor Method of the rp2.DMA Class

The constructor of the rp2.DMA class is as follows:

rp2.DMA()

Instantiate a DMA controller channel.

2.2 Other Methods of the rp2.DMA Class

The rp2.DMA class has other methods:

Method

Description

DMA.config(read=None, write=None, 

count=None, ctrl=None, trigger=False)

Configure the DMA channel, which is used to set the read/write address, transfer count and control parameters, and supports optional immediate transfer triggering. The descriptions of the parameters are as follows:

  • read: This specifies the address from which the DMA controller starts reading data, or the source object that provides the data; it can be either an integer address (representing a memory address) or an object that supports the buffer protocol (such as bytearray, etc.), and the DMA will read data starting from this address.
  • write: This is the address where the DMA controller starts writing data, or the target object to which data is written. It can be an integer address (representing a memory address) or an object that supports the buffer protocol, to which the DMA will write the read data.
  • count: The total number of transfers to be performed, i. e., the total number of DMA transfers. Note that this refers to the total number of transfers, not the number of bytes; if a single transfer is 2 bytes or 4 bytes wide, the actual amount of data to be transferred needs to be multiplied by the corresponding coefficient according to the width, which means that the size of the buffer should be adjusted according to the total amount of data actually transferred.
  • ctrl: The value of the DMA control register. This is an integer, and the DMA.pack_ctrl () method is typically used to pack configuration options. This register contains configuration information about how the DMA channel performs transfers, such as transfer width, address increment mode, etc.
  • trigger: Whether to immediately start DMA transfer:
    • If set to True, the DMA channel will start transmission immediately after the configuration is complete
    • If set to False, only the registers will be configured, and the transmission will not start automatically.

DMA.irq(handler=None, hard=False)

Returns the interrupt object of the DMA channel and allows configuration of the interrupt handler. Through this method, you can monitor the status of the DMA channel and trigger an interrupt when the transfer is completed or an error occurs.

The parameters are defined as follows:

  • handler : A callback function for interrupt handling. This callback will be invoked when the DMA transfer completes or a specific event occurs; if no callback needs to be set, you can set this parameter to None.
  • hard : indicates whether it is hard interrupt processing
    • If set to True, hard interrupts will be used, which means the handler will execute in the hardware interrupt context, making it suitable for scenarios with high real-time requirements.
    • If set to False (the default value), a soft interrupt will be used, and other high-priority tasks will not be preempted during execution.

DMA.close()

This method is used to release the occupancy of the DMA channel and unbind the interrupt handler; after calling this method, the current DMA object will be unavailable and you must reinitialize it or create a new DMA object to proceed with subsequent operations.

DMA.pack_ctrl(default=None, **kwargs)

Pack the value of the DMA control register, where the control parameters include transfer size, address increment, etc.

The optional parameters are as follows:

  • enable: Set to True to enable the DMA channel (default: True)
  • high_pri: Set this channel to high priority (default: False)
  • size: Set the transfer size: 0 = byte, 1 = double-byte, 2 = quad-byte

    (default value is 2, i. e., 4-byte transmission)

  • inc_read: Set to True to increment the read address after each transmission (default: True)
  • inc_write: Set to True to increment the write address after each transmission (default: True)
  • ring_size: Defines how many of the least significant bits of the address register will change when the address is incremented, which forms the size of the ring buffer. For example, if ring_size is set to 8, the 8 least significant bits of the address register will vary, meaning the address will wrap around on a 256-byte boundary
  • ring_sel: Set to False to apply ring_size to read addresses, set to True to apply it to write addresses
  • chain_to: Set this to the channel number that will be triggered after the current channel completes transmission. Setting this to the channel number of this DMA object will disable chaining transmission (default).
  • treq_sel: Transfer request signal selection
  • irq_quiet: Set to True to disable interrupt generation at the end of each transfer (default: True). When set to True, the DMA will not generate an interrupt at the end of each individual transfer; an interrupt will only be generated when a zero value is written to the trigger register to terminate a series of chained transfers. This design avoids frequent interrupt generation at the end of each individual transfer, thereby optimizing overall system performance.
  • bswap: When set to True, reverses the bytes in a word or half-word before writing (default: True)
  • sniff_en: Set to True to allow data to be accessed by the chip's sniff hardware (default: False)
  • write_err: Set to True to clear a previously reported write error
  • read_err: Set to True to clear previously reported read errors

DMA.unpack_ctrl(value)

Unpack the DMA control register value and return a dictionary containing all control data bits.

The parameters are defined as follows:

  • value: Control register value to be unpacked

The returned Attribute–Value Pair data bits are as follows:

  • enable: Enable or disable the DMA channel
  • high_pri: Whether the priority of the DMA channel is set to high
  • size: the size of data transmission (0 = byte, 1 = double byte, 2 = quad byte)
  • inc_read: Whether to increment the read address after each transmission
  • inc_write: Whether to increment the write address after each transmission
  • ring_size: The bit size for address wrapping; if set to zero, address wrapping will be disabled
  • ring_sel: Controls whether ring_size is applied to the read address or the write address
  • chain_to: Channel number for chain triggering
  • treq_sel: Selection of transmission request signal
  • irq_quiet: whether to disable interrupt generation at the end of each transfer
  • bswap: Whether to reverse the byte order before writing
  • sniff_en: Enable sniff hardware access or not
  • write_err: Whether to report write errors
  • read_err: Whether to report read errors

DMA.active([value])

Query or set whether the DMA channel is in an active state.

2.3 Attributes of the rp2.DMA Class

The rp2.DMA class also has several methods:

Attribute

Description

DMA.read

The DMA.read property reflects the read address for the next bus transfer operation. This property can be assigned an integer address or an object that supports the buffer protocol (such as bytearray, memoryview, etc.), and the assignment takes effect immediately.

DMA.write

The DMA.write property reflects the write address for the next bus transfer operation. This property can be assigned either an integer address or an object that supports the buffer protocol, and the assignment takes effect immediately.

DMA.count

Used to read or set the transfer count of the DMA channel:

  • Read DMA.count: it returns the number of remaining bus transfers in the current transfer sequence, that is, how many transfers still need to be completed in the current DMA transfer operation
  • Writing to DMA.count: When assigning a value to DMA.count, the total number of transfers for the subsequent transfer sequence is set

DMA.ctrl

Reflects the current value of the DMA control register, which can be packaged and written via DMA.pack_ctrl (), and the returned value can be unpacked via the DMA.unpack_ctrl () method.

DMA.channel

Returns the current DMA channel number, which can be used for DMA linking.

DMA.registers

DMA.registers is an array-like object that allows direct access to the DMA channel registers of the RP2040. Indexing is performed in words rather than bytes, which means the index of a register is the result of dividing the register address offset by 4.

3. Application Examples

3.1 DMA Class Implements Memory-to-Memory Data Transfer

The following code can be found in the elegance-devkit v1\Demo\66 DMA_MemoryToMemory folder within the resource package we provide.

In the following code, we use DMA to transfer data from a source array to a destination array, which eliminates the need for the CPU to participate in copying each byte, thus reducing the CPU workload and improving transmission efficiency. Meanwhile, we also compare the time-consuming difference between DMA transfer and array slice copying.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/7 10:50 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : DMA experiment, memory-to-memory transfer

# ======================================== Import Modules =========================================

# Import the DMA controller from the rp2 library
from rp2 import DMA
# Import the addressof function, used to get the memory address of data
from uctypes import addressof
# Import the array module, used to create arrays
from array import array
# Import time-related modules
import time

# ======================================== Global Variables ============================================

# Create an array as the source data, with data type unsigned 32-bit integers (I), and initialize the data
# From 0 to 1023, 1024 elements in total
source_data = array("I", range(1024))
# Create another array as the destination data, initialized as empty data space with the same size as the source data
destination_data = array("I", [0] * len(source_data))

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information indicating the start of the main program
print("FreakStudio: DMA Memory to Memory Test ")

# Initialize the DMA object
dma = DMA()

# Set the DMA control register, using the pack_ctrl method to pack the control register; size=2 means transferring 32-bit words
ctrl = dma.pack_ctrl(size=2)

# Configure the DMA control register to set the data transfer mode
dma.config(
    read=addressof(source_data),        # Specify the source address (memory address of the source data)
    write=addressof(destination_data),  # Specify the destination address (memory address of the destination data)
    count=len(source_data),             # Length of data to transfer (in number of elements)
    ctrl=ctrl,      # Control register configuration
    trigger=False   # Do not start the transfer immediately
)

# ========================================  Main Program  ==========================================

# Print debug data, start DMA transfer
print("Start DMA")

# Test DMA transfer speed
# Record start time
start_time = time.ticks_us()
# Start DMA transfer
dma.active(1)
# Check whether DMA has finished the transfer; the transfer is complete when dma.count is 0
while dma.count > 0:
    pass
# Record end time
end_time = time.ticks_us()
# Calculate elapsed time
dma_time = time.ticks_diff(end_time, start_time)
print("DMA Transfer Time (us): ", dma_time)

# Print debug data to indicate the transfer is complete
print("DMA Finished")

# Print the destination data after the transfer to verify it is correct
print("Source Data: ", source_data)
print("Destination Data: ", destination_data)

# Test array slice copy speed
start_time = time.ticks_us()
destination_data[:] = source_data[:]
end_time = time.ticks_us()
array_time = time.ticks_diff(end_time, start_time)
print("Array Slice Copy Time (us): ", array_time)

Here, we first create two arrays:

Then configure the created DMA channel object:

19 DMA Direct Memory Access - Document Tutorial Draft

It can be seen that we set its read address and write address to increment, do not generate an interrupt at the end of each transmission but generate an interrupt after reading a zero value, and the data size of a single transmission is four bytes (32-bit data)

In the main program, after starting the DMA transfer, we use while dma.count > 0: to check whether the transfer is completed. dma.count indicates the number of data remaining to be transferred by DMA; when it becomes 0, the transfer is complete. Finally, we print the source data and destination data to verify whether DMA has successfully transferred the data from the source array to the destination array.

At the same time, record and proofread the time consumed by DMA transmission, and then test the array slice copying speed.

Burn the code, and the output is as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

3.1 Application Experiment.mp4 19.5 MB

As can be seen, we have successfully implemented data transfer from memory to memory using DMA, and the time taken for 1024 elements is 104 us, while the time taken for the slice copy operation is 314 us. When dealing with a large amount of Big data, the DMA data transfer speed is much faster than that of the slice copy operation; if we increase the data length to 4096 elements, the time taken for DMA transfer is 110 us, and the time taken for the slice copy operation is 923 us, making the speed difference even more pronounced.

Direct assignment is essentially reference copying

Here, a common pitfall to note is that in Python, destination_data = source_data does not copy the data; instead, it makes destination_data and source_data point to the same memory address, which means modifying the content in either destination_data or source_data will simultaneously affect the other variable.

The above code implements copying the content of source_data byte by byte to destination_data; the two occupy different Memory Spaces and do not affect each other.

3.2 DMA Class Implements Memory-to-Peripheral Data Transfer

3.2.1 Preparations Before the Experiment

In the following code, we have customized a DMA_UART_Tx class, which is used to implement efficient serial data transmission via UART and DMA on the Raspberry Pi Pico. DMA transfers data from the source address (memory) to the destination address (the UART data register).

In the following experiment, we need to insert the Fengya No.1 board-Grove interface expansion board into the Fengya No.1 board-universal compatible expansion board , and use the HY2.0-4P wiring to connect the Fengya No.1 board-Grove interface expansion board 's UART1 interface and GraftSense-based USB to TTL module based on CH340K 's UART1 interface:

Then use a USB-A to Mini USB data cable to connect the USB port on the GraftSense - USB to TTL module based on CH340K to the computer. The physical connection diagram is shown below:

19 DMA Direct Memory Access - Document Tutorial Draft

In addition, we first need to connect the MiniUSB data cable to the serial port on Fengya No. 1 Board - Universal Compatible Expansion Board. Here, GP0 and GP1 are the default pins of the hardware serial port UART0 of the Raspberry Pi Pico:

19 DMA Direct Memory Access - Document Tutorial Draft

The physical image after insertion is as follows:

The pin connections are as follows:

Raspberry Pi Pico GPIO Pins

Connected electronic modules

Description of Application

GP0

Onboard USB-to-TTL chip

serves as the TX (transmit) pin of UART0

GP1

Onboard USB-to-TTL chip

serves as the RX (receive) pin of UART0

GP4

External USB-to-TTL module

Serve as the side set pins and output pins (for transmission) of finite-state machine 0

GP5

External USB-to-TTL module

Connect to an external USB-to-TTL module (presumably the receiving pin)

3.2.2 Implementation of Custom Serial Port DMA Transmission Class

Here, we first place the custom UART serial port DMA transmission class into a separate file:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/7 11:56 PM
# @Author  : Li Qingshui
# @File    : dma_uart_tx.py       
# @Description : Custom UART DMA transfer

# ======================================== Import Modules =========================================

# Import the DMA controller from the rp2 library
from rp2 import DMA
# Import time-related modules
import time
# Import hardware-related modules
from machine import UART
# Import the module for reading and writing 32-bit memory
from machine import mem32
# Import the addressof function, used to get the memory address of data
from uctypes import addressof

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# Custom DMA UART transmit class: uses DMA to transfer data to the UART for sending
class DMA_UART_Tx:
    """
    DMA_UART_Tx class, used to transfer data to the UART through DMA (Direct Memory Access) for sending.
    This class wraps the configuration and operation of DMA and UART, and supports a transfer mode with 8 data bits, no parity bit, and 1 stop bit.
    UART0 is used by default, with a baud rate of 115200, TX pin 0, and RX pin 1.

    Attributes:
        uart_num (int): UART number, 0 for UART0, 1 for UART1.
        baudrate (int): Baud rate, default is 115200.
        tx_pin (int): TX pin number, default is 0.
        rx_pin (int): RX pin number, default is 1.
        uart (UART): UART instance, used to configure and operate the UART.
        dma (DMA): DMA instance, used to configure and operate the DMA.
        UART_BASE (int): UART register base address.
        UART_UARTDR (int): UART data register address.
        UART_UARTFR (int): UART flag register address.
        UART_UARTDMACR (int): UART DMA control register address.

    Methods:
        __init__(self, uart_num=0, baudrate=115200, tx_pin=0, rx_pin=1):
            Initialize the DMA UART class.
        is_transmit_fifo_full(self):
            Check whether the UART transmit FIFO is full.
        is_transmit_fifo_empty(self):
            Check whether the UART transmit FIFO is empty.
        is_buffer_protocol(obj):
            Determine whether an object is a buffer protocol object.
        enable_uart_tx_dma(self):
            Enable the UART transmit DMA function.
        dma_transmit(self, buf, wait_func=None, callback=None, blocking=False):
            Use DMA to transfer data to the UART.
    """
    def __init__(self, uart_num: int = 0, baudrate: int = 115200, tx_pin: int = 0, rx_pin: int = 1) -> None:
        """
        Initialize the DMA UART class. Currently only the transfer mode with 8 data bits, no parity bit, and 1 stop bit is supported.
        UART0 is used by default, with a baud rate of 115200, TX pin 0, and RX pin 1.

        Args:
            uart_num (int): Select UART0 or UART1, default is 0.
            baudrate (int): Baud rate, default is 115200.
            tx_pin (int): TX pin number, default is 0.
            rx_pin (int): RX pin number, default is 1.

        Raises:
            ValueError: If the UART number or baud rate is invalid.
        """
        # Check whether the UART is available
        if uart_num not in (0, 1):
            raise ValueError("UART number must be 0 or 1")
        # Check whether the baud rate is a valid value
        if baudrate not in (9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600):
            raise ValueError("Invalid baudrate")

        self.uart_num = uart_num
        self.baudrate = baudrate
        self.tx_pin = tx_pin
        self.rx_pin = rx_pin

        # Initialize UART
        self.uart = UART(self.uart_num, baudrate=self.baudrate, tx=self.tx_pin, rx=self.rx_pin)
        self.uart.init(baudrate=self.baudrate, bits=8, parity=None, stop=1, timeout=100)

        # Initialize DMA
        self.dma = DMA()

        # Define UART register addresses: for UART0 the address is 0x40034000, otherwise 0x40038000
        self.UART_BASE = 0x40034000 if self.uart_num == 0 else 0x40038000

        # Address information of the UARTDR, UARTFR, UARTCR and UARTDMACR registers in the UART peripheral
        self.UARTDR_OFFSET = 0x000
        self.UARTFR_OFFSET = 0x018
        self.UARTDMACR_OFFSET = 0x048

        self.UART_UARTDR = self.UART_BASE + self.UARTDR_OFFSET
        self.UART_UARTFR = self.UART_BASE + self.UARTFR_OFFSET
        self.UART_UARTDMACR = self.UART_BASE + self.UARTDMACR_OFFSET

        # Enable the DMA transfer function
        self.enable_uart_tx_dma()

    def is_transmit_fifo_full(self) -> bool:
        """
        Check whether the UART transmit FIFO is full.

        Returns:
            bool: True means full, False means not full.
        """

        # Read the value of the UARTFR register
        reg_value = mem32[self.UART_UARTFR]
        # Extract the value of the TXFF bit (bit 5)
        txff_bit = (reg_value >> 5) & 0x1

        # Determine whether the TXFF bit is 1 (whether the FIFO is full)
        return txff_bit == 1

    def is_transmit_fifo_empty(self) -> bool:
        """
        Check whether the UART transmit FIFO is empty.

        Returns:
            bool: True means empty, False means not empty.
        """

        # Read the value of the UARTFR register
        reg_value = mem32[self.UART_UARTFR]
        # Extract the value of the TXFE bit (bit 7)
        txfe_bit = (reg_value >> 7) & 0x1

        # Determine whether the TXFE bit is 1 (whether the FIFO is empty)
        return txfe_bit == 1

    @staticmethod
    def is_buffer_protocol(obj: object) -> bool:
        """
        Determine whether an object is a buffer protocol object.

        Args:
            obj (object): The object passed in.

        Returns:
            bool: Returns True if it is a buffer protocol object, otherwise False.
        """
        try:
            # Try to use memoryview to create a buffer view of the object
            memoryview(obj)
            return True
        except TypeError:
            return False

    def enable_uart_tx_dma(self) -> None:
        """
        Enable the UART transmit DMA function by setting the TXDMAE bit of the UARTDMACR register.
        """
        reg_value = mem32[self.UART_UARTDMACR]
        reg_value |= (1 << 1)
        mem32[self.UART_UARTDMACR] = reg_value

    def dma_transmit(self, buf: object, wait_func: callable = None, callback: callable = None,
                     blocking: bool = False) -> int:
        """
        Use DMA to transfer data to the UART.

        Args:
            buf (object): The byte data to transfer; must be a buffer protocol object.
            wait_func (callable): Callback function called while the transfer is in progress, optional.
            callback (callable): Callback function called when the transfer is complete, optional.
            blocking (bool): Whether to block and wait for the transfer to complete, optional, default is False.

        Returns:
            int: Elapsed time, in microseconds.

        Raises:
            Exception: If wait_func is passed in non-blocking mode, or buf is not a buffer protocol object.
        """

        # If non-blocking mode is selected, wait_func should not be passed in
        if blocking == False and wait_func is not None:
            raise Exception("Blocking mode should not have wait_func!")

        # Determine whether buf is a buffer protocol object
        if DMA_UART_Tx.is_buffer_protocol(buf) == False:
            raise Exception("buf must be a buffer protocol object!")

        # 20 is the number of the DREQ_UARTO_TX request signal, 22 is the number of the DREQ_UART1_TX request signal
        UART_DREQ = 20 if self.uart_num == 0 else 22

        # Set the DMA control register
        ctrl = self.dma.pack_ctrl(enable=True,          # Enable DMA
                                  size=0,               # Single transfer size of 8 bits (byte)
                                  inc_read=True,        # Read address increments
                                  inc_write=False,      # Write address does not increment
                                  treq_sel=UART_DREQ    # Set the DMA trigger signal
                                  )

        # Configure DMA
        self.dma.config(read=addressof(buf),     # Source address, i.e. the memory address of the data buffer
                        write=self.UART_UARTDR,  # Destination address, i.e. the address of the UART data register
                        count=len(buf),          # Number of bytes to transfer
                        ctrl=ctrl,               # DMA control register configuration
                        trigger=True             # Trigger the DMA transfer immediately
                        )

        # Record start time
        start_time = time.ticks_us()
        # Start DMA transfer
        self.dma.active(1)

        # Blocking mode, wait for the DMA transfer to complete
        if blocking == True:
            # Wait for the DMA transfer to complete
            while self.dma.active():
                # Check whether the TXFE bit of the UARTFR register is set
                if not self.is_transmit_fifo_empty():
                    # If the TXFE bit is not 1, the FIFO is not empty
                    if wait_func is not None:
                        # Execute the user-defined callback function
                        wait_func()

        if callback is not None:
            # Wait for the DMA transfer to finish, then execute the user-defined callback
            callback()

        # Record end time
        end_time = time.ticks_us()  # Record end time
        # Return elapsed time
        return time.ticks_diff(end_time, start_time)

# ======================================== Initialization ==========================================

# ========================================  Main Program  ===========================================

DMA_UART_Tx class provides the following methods and properties:

19 DMA Direct Memory Access - Document Tutorial Draft
19 DMA Direct Memory Access - Document Tutorial Draft

Steps to implement data transfer between memory and peripherals using DMA

Here, when we use DMA to implement mutual data transmission between memory and peripherals, the general steps can be summarized as follows:

  1. Enable the DMA mode and DMA request signal of the peripheral: Enable the DMA function and DMA request signal by configuring the corresponding register (DREQ), which is sent by the peripheral to the DMA controller to indicate that the peripheral has data to be transferred
  2. Enable and configure the FIFO of the peripheral: Set the corresponding registers to enable the FIFO, and configure the FIFO trigger threshold; the DMA can automatically write data from the memory to the FIFO or read data from the FIFO to the memory according to the full/empty status of the FIFO
  3. Use DMA to complete data transmission between the peripheral and its corresponding FIFO register: configure the source address and destination address of the DMA controller data transmission, set the transmission direction and data size, and then start the DMA transmission

Here, let’s first take a look at the structure of the UART peripheral in the Raspberry Pi Pico:

19 DMA Direct Memory Access - Document Tutorial Draft

Here, the 32x8 transmit FIFO and 32x12 receive FIFO shown in the diagram are part of the UART hardware module, but they are not exposed to the user in the form of direct standalone registers. We need to indirectly operate the FIFO via UARTDR (the data register), which allows reading and writing data, and manages the queue operations of the FIFO buffer through internal hardware:

19 DMA Direct Memory Access - Document Tutorial Draft

By configuring the UARTLCR_H register, the FIFO of the UART can be enabled:

19 DMA Direct Memory Access - Document Tutorial Draft

Actually, after creating and configuring an instance of the UART class in MicroPython, the FIFO and the FIFO interrupt trigger threshold have already been enabled:

19 DMA Direct Memory Access - Document Tutorial Draft

The status of the FIFO is typically monitored via the flag register UARTFR (Flag Register), which contains flag bits indicating whether the FIFO is empty or full. Accordingly, the status of the FIFO can be determined by reading these flag bits, so as to perform corresponding data transmission operations:

19 DMA Direct Memory Access - Document Tutorial Draft

The DMA in the serial port peripheral controls and coordinates data transmission via UARTDMACR, and we need to enable its TXDMAE data bit here:

19 DMA Direct Memory Access - Document Tutorial Draft

Here, the process of implementing DMA data transmission for the UART peripheral via DMA is as follows: first, enable the TXDMAE data bit in the transmit DMA of the UART peripheral, then use DMA to continuously enable the DATA data bit of the UARTDR register for data transfer from memory to the UART peripheral.

When initializing the DMA_UART_Tx class, we perform the following operations:

19 DMA Direct Memory Access - Document Tutorial Draft

When reading from and writing to register data, we use machine.mem32 to read and write 32-bit register data. By passing the register address value into it, we can access and configure registers just like accessing memory.

The main method we use DMA to implement serial port data transmission is dma_transmit:

def dma_transmit(self, buf: object, wait_func: callable = None, callback: callable = None,
                 blocking: bool = False) -> int:
    """
    Use DMA to transfer data to the UART.

    Args:
        buf (object): The byte data to transfer; must be a buffer protocol object.
        wait_func (callable): Callback function called while the transfer is in progress, optional.
        callback (callable): Callback function called when the transfer is complete, optional.
        blocking (bool): Whether to block and wait for the transfer to complete, optional, default is False.

    Returns:
        int: Elapsed time, in microseconds.

    Raises:
        Exception: If wait_func is passed in non-blocking mode, or buf is not a buffer protocol object.
    """
    ... ...

Here, we need to pass four parameters into it: the byte data to be transmitted, the callback function during transmission, the callback function after transmission is completed, and the flag indicating whether to block and wait for the transmission to finish.

When the blocking mode is selected, the method will block and not return until the DMA data transfer is completed; conversely, when set to the non-blocking mode, it will return immediately after the DMA data transfer is initiated.

# Blocking mode, wait for the DMA transfer to complete
if blocking == True:
    # Wait for the DMA transfer to complete
    while self.dma.active():
        # Check whether the TXFE bit of the UARTFR register is set
        if not self.is_transmit_fifo_empty():
            # If the TXFE bit is not 1, the FIFO is not empty
            if wait_func is not None:
                # Execute the user-defined callback function
                wait_func()

In this method, we first perform validation on the input parameters:

# If non-blocking mode is selected, wait_func should not be passed in
if blocking == False and wait_func is not None:
    raise Exception("Blocking mode should not have wait_func!")
# Determine whether buf is a buffer protocol object
if DMA_UART_Tx.is_buffer_protocol(buf) == False:
    raise Exception("buf must be a buffer protocol object!")

Here, we define a static method to determine whether it is a buffer protocol object:

@staticmethod
def is_buffer_protocol(obj: object) -> bool:
    """
    Determine whether an object is a buffer protocol object.

    Args:
        obj (object): The object passed in.

    Returns:
        bool: Returns True if it is a buffer protocol object, otherwise False.
    """
    try:
        # Try to use memoryview to create a buffer view of the object
        memoryview(obj)
        return True
    except TypeError:
        return False

We will configure the DMA request signal according to the number of the serial port peripheral in use.

# 20 is the number of the DREQ_UARTO_TX request signal, 22 is the number of the DREQ_UART1_TX request signal
UART_DREQ = 20 if self.uart_num == 0 else 22

The DMA request signal numbers are shown in the following figure:

19 DMA Direct Memory Access - Document Tutorial Draft

Next, we configure the DMA control register and channels:

# Set the DMA control register
ctrl = self.dma.pack_ctrl(enable=True,          # Enable DMA
                          size=0,               # Single transfer size of 8 bits (byte)
                          inc_read=True,        # Read address increments
                          inc_write=False,      # Write address does not increment
                          treq_sel=UART_DREQ    # Set the DMA trigger signal
                          )

# Configure DMA
self.dma.config(read=addressof(buf),     # Source address, i.e. the memory address of the data buffer
                write=self.UART_UARTDR,  # Destination address, i.e. the address of the UART data register
                count=len(buf),          # Number of bytes to transfer
                ctrl=ctrl,               # DMA control register configuration
                trigger=True             # Trigger the DMA transfer immediately
                )

Set the source address of the DMA to the memory address of the data buffer, the destination address to the address of the UART data register, the size of a single data item to 8 bits (i. e., one byte), and enable address increment for reading so as to continuously read the data in buf.

Before initiating DMA data transfer, record the start time of the program; after the DMA transfer is completed or the DMA startup finishes, record the end time, and return the time consumed by this part:

# Record start time
start_time = time.ticks_us()
# Start DMA transfer
self.dma.active(1)

# Blocking mode, wait for the DMA transfer to complete
if blocking == True:
    # Wait for the DMA transfer to complete
    while self.dma.active():
        # Check whether the TXFE bit of the UARTFR register is set
        if not self.is_transmit_fifo_empty():
            # If the TXFE bit is not 1, the FIFO is not empty
            if wait_func is not None:
                # Execute the user-defined callback function
                wait_func()

if callback is not None:
    # Wait for the DMA transfer to finish, then execute the user-defined callback
    callback()

# Record end time
end_time = time.ticks_us()  # Record end time
# Return elapsed time
return time.ticks_diff(end_time, start_time)

Here, we use the is_transmit_fifo_empty method to determine whether the FIFO in UART transmission is empty, and extract the TXFE bit to check the FIFO status, so as to judge the current sending status of serial port data:

def is_transmit_fifo_empty(self) -> bool:
    """
    Check whether the UART transmit FIFO is empty.

    Returns:
        bool: True means empty, False means not empty.
    """

    # Read the value of the UARTFR register
    reg_value = mem32[self.UART_UARTFR]
    # Extract the value of the TXFE bit (bit 7)
    txfe_bit = (reg_value >> 7) & 0x1

    # Determine whether the TXFE bit is 1 (whether the FIFO is empty)
    return txfe_bit == 1

dma_transmit () The complete Sequence Diagram of the method is shown below:

19 DMA Direct Memory Access - Document Tutorial Draft

3.2.3 Experimental Routines

The following code can be found in the elegance-devkit v1\Demo\67 DMA_MemoryToPeripheral folder within the resource package we provide.

The main program we tested for the DMA_UART_Tx class is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/7 11:26 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : DMA class experiment, memory-to-peripheral transfer: DMA writes data from memory to the UART

# ======================================== Import Modules =========================================

# Import the math-related module
import math
# Import time-related modules
import time
# Import the custom UART DMA transfer class
from dma_uart_tx import DMA_UART_Tx
# Import hardware-related modules
from machine import UART

# ======================================== Global Variables ============================================

# Data buffer, data to be sent: sine wave data
# Configure sine wave parameters
amplitude = 127     # Amplitude, maximum value of the sine wave (0-255); 127 is half of the unsigned 8-bit range, the peak
offset = 128        # Offset, ensures the waveform stays between 0 and 255
num_samples = 1000  # Number of sine wave sample points
frequency = 1       # Frequency, can be adjusted as needed

# Generate sine wave data and put it into a bytearray
sin_wave = bytearray(num_samples)

for i in range(num_samples):
    # Calculate the angle of the current sample point
    angle = 2 * math.pi * frequency * (i / num_samples)
    # Generate the corresponding sine wave value, scale it up and add the offset to fit the bytearray (0-255) range
    sine_value = int(amplitude * math.sin(angle) + offset)
    # Put the sine value into the bytearray buffer
    sin_wave[i] = sine_value

# Run time of sending data over the serial port with DMA
uart_dma_time = 0
# Run time of sending data over the serial port without DMA
uart_non_dma_time = 0

# ======================================== Functions ============================================

# DMA transfer wait callback function
def uart_dma_tx_wait_func() -> None:
    """
    DMA transfer wait callback function.

    Returns:
        None
    """
    print("wait dma transmit complete")

# DMA transfer complete callback function
def uart_dma_tx_complete_callback() -> None:
    """
    DMA transfer complete callback function.

    Returns:
        None
    """
    print("uart dma transmit complete")

# Append the newline '\r\n' after each element of the bytearray
def add_newline_after_each_byte(buf: bytearray) -> bytearray:
    """
    Append the newline '\r\n' after each element of the bytearray.

    Args:
        buf (bytearray): The input bytearray.

    Returns:
        bytearray: Returns a new bytearray containing '\r\n'.

    Raises:
        TypeError: If the input parameter is not of type bytearray.
    """

    # Check whether the input parameter is a bytearray
    if not isinstance(buf, bytearray):
        raise TypeError("buf must be a bytearray")

    # Create a new bytearray to hold the result
    expanded_buf = bytearray()

    # Iterate over each byte of the input buffer
    for byte in buf:
        # Append the original data byte
        expanded_buf.append(byte)
        # Append the ASCII value of '\r' (13)
        expanded_buf.append(13)
        # Append the ASCII value of '\n' (10)
        expanded_buf.append(10)

    return expanded_buf

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information indicating the start of the main program
print("FreakStudio: DMA Memory to Peripheral Test ")

# Instantiate the DMA_UART_Tx class, assuming UART0, baud rate 115200, TX pin 0, RX pin 1
dma_uart = DMA_UART_Tx(uart_num=0, baudrate=115200, tx_pin=0, rx_pin=1)

# Create the serial port object, set the baud rate to 115200
uart = UART(1, 115200)
# Initialize the uart object with a baud rate of 115200, 8 data bits, no parity bit, and 1 stop bit
# Set the receive pin to GPIO5 and the transmit pin to GPIO4
# Set the serial port timeout to 100ms
uart.init(baudrate  = 115200,
          bits      = 8,
          parity    = None,
          stop      = 1,
          tx        = 4,
          rx        = 5,
          timeout   = 100)

# ========================================  Main Program  ===========================================

# Transmit data over the serial port using DMA
# Transmit data in blocking mode
dma_uart.dma_transmit(buf=sin_wave, wait_func=uart_dma_tx_wait_func, callback=uart_dma_tx_complete_callback, blocking=True)
# Transmit data in non-blocking mode and record the run time
uart_dma_time = dma_uart.dma_transmit(buf=sin_wave, blocking=False)

# Transmit data without DMA
# Record the start time
start_time = time.ticks_us()
# Transmit data
uart.write(sin_wave)
# Record the end time
end_time = time.ticks_us()
# Calculate the run time
uart_non_dma_time = time.ticks_diff(end_time, start_time)

# Print debug data to indicate the transfer is complete
print("DMA Finished,run time: %d us" % uart_dma_time)
print("Non-DMA Finished,run time: %d us" % uart_non_dma_time)

Here, we first declare a buffer, and write sine wave data with an amplitude of 127, a DC offset of 128,1000 sampling points and a frequency of 1 Hz into it; then we define uart_dma_time and uart_non_dma_time variables to record the time taken for data transmission with and without DMA. Meanwhile, we set up two callback functions to output debug information during and after the DMA transmission.

The timing sequence of the entire program is shown as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

Next, we open the SerialPlot software and select the port corresponding to the serial port of the Raspberry Pi Pico:

19 DMA Direct Memory Access - Document Tutorial Draft

The data format is set as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

Burn the code, open the terminal, and the following content will be displayed:

19 DMA Direct Memory Access - Document Tutorial Draft

3.2.3 Terminal.mp4 2.1 MB

It can be seen that the CPU occupancy rate of serial port data transmission implemented by DMA is much lower than that of ordinary serial port data transmission. In non-blocking mode, the callback function will be called after the DMA transfer is completed, and no CPU polling is required.

We can also export the CSV file of the data to check whether all the data has been completely received:

19 DMA Direct Memory Access - Document Tutorial Draft

data.csv 4 KB

3.2.3 Waveform.mp4 8.8 MB

3.3 DMA Class Implementation for Peripheral-to-Memory Data Transfer

3.3.1 Preparations before the Experiment

In the following experiment, we need to insert the Fengya No. 1 Board - Grove Interface Expansion Board into the Fengya No. 1 Board - Universal Compatible Expansion Board, and meanwhile use a PH2.0-4P cable to connect the AIN0 interface on the Fengya No. 1 Board - Grove Interface Expansion Board and the analog output interface on the GraftSense - Slide Potentiometer Module:

19 DMA Direct Memory Access - Document Tutorial Draft

In addition, we first need to connect the MiniUSB data cable to the serial port on Fengya No. 1 Board - Universal Compatible Expansion Board. Here, GP0 and GP1 are the default pins of the hardware serial port UART0 of the Raspberry Pi Pico:

19 DMA Direct Memory Access - Document Tutorial Draft

The physical image after insertion is as follows:

The pin connections are shown in the following table:

Module / DevicePin / InterfaceConnection targetTarget pin / Interface
Fengya No. 1 board - Grove interface expansion boardAIN0 interfaceGraftSense - Slide Rheostat ModuleAnalog output interface
Fengya No. 1 board - Grove interface expansion boardAIN0 internal connectionRaspberry Pi Pico (core of the Fengya No. 1 board)GP26 (ADC0)
Raspberry Pi Pico (core of the Fengya No. 1 board)GP0 (UART0_TX)Fengya No. 1 board - Universal compatible expansion boardSerial port TX pin
Raspberry Pi Pico (core of the Fengya No. 1 board)GP1 (UART0_RX)Fengya No. 1 board - Universal compatible expansion boardSerial port RX pin
Fengya No. 1 board - Universal compatible expansion boardSerial port interfaceMiniUSB cableUSB male end
Fengya No. 1 board - Grove interface expansion board-Fengya No. 1 board - Universal compatible expansion board-

3.3.2 Implementation of Custom Analog-to-Digital Conversion DMA Transfer Class

Here, we define a DMA_ADC_Transfer class, which is used to implement the transmission of ADC conversion data from the FIFO register to memory via DMA on the Raspberry Pi Pico.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/8 11:15 PM
# @Author  : Li Qingshui
# @File    : dma_adc_trans.py.py       
# @Description : Custom DMA transfer class for ADC data acquisition

# ======================================== Import Modules =========================================

# Import hardware-related modules
from machine import ADC
# Import the addressof function, used to get the memory address of data
from uctypes import addressof
# Import DMA-related modules
from rp2 import DMA
# Import the module for reading and writing 32-bit memory
from machine import mem32

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# Custom ADC class that transfers data via DMA
class DMA_ADC_Transfer:
    """
    DMA_ADC_Transfer class, used for efficient ADC data transfer via DMA.
    This class encapsulates ADC configuration, DMA transfer, FIFO control and other functions, enabling high-speed sampling into a user-provided buffer.

    This class supports free-running sampling mode and a configurable ADC sample rate, and provides both blocking and non-blocking modes for DMA transfer.

    Attributes:
        buf (bytearray): Buffer used to store ADC sample data.
        sample_rate (int): Desired ADC sample rate (Hz).
        adc (ADC): ADC instance object, used for analog-to-digital conversion.
        dma (DMA): DMA controller instance object.

    Constants:
        DREQ_ADC (int): DMA trigger signal ID of the ADC.
        ADC_BASE (int): Base address of the ADC FIFO registers.
        CS_REG (int): Address offset of the control register (CS).
        RESULT_REG (int): Address offset of the result register (RESULT).
        FCS_REG (int): Address offset of the FIFO control register (FCS).
        DIV_REG (int): Address offset of the sample divider register (DIV).
        FIFO_REG (int): Address offset of the FIFO data register (FIFO).
        FIFO_THRESH (int): Threshold at which the ADC FIFO triggers a DMA transfer.
        ADC_CLOCK_FREQ (int): ADC clock frequency, assumed to be 48MHz.

    Methods:
        __init__(self, buf: bytearray, sample_rate: int = 1000, adc_id: int = 0):
            Initialize an instance of the DMA_ADC_Transfer class and configure the ADC and DMA.

        configure_adc_fifo(self) -> None:
            Configure the ADC FIFO so that it can work with DMA for data transfer.

        start_adc_continuous(self) -> None:
            Start the ADC free-running sampling mode so that it keeps acquiring data continuously.

        configure_adc_sample_rate(self, sample_rate: int) -> None:
            Configure the ADC sample rate and set the corresponding clock divider.

        stop_dma_adc_fifo(self) -> None:
            Stop the DMA transfer and ADC sampling, ensuring the sampling process ends safely.

        start_dma_transfer(self, wait_func: callable = None, complete_callback: callable = None, blocking: bool = True) -> None:
            Start the DMA transfer, with the option to block until it completes or to specify a transfer-complete callback.

        close(self) -> None:
            Shut down the DMA transfer and release the ADC resources.
    """

    # DMA trigger signal of the ADC
    DREQ_ADC = 36

    # Base address of the ADC FIFO registers
    ADC_BASE = 0x4004C000
    # CS register offset is 0x00
    CS_REG = ADC_BASE + 0x00
    # RESULT register offset is 0x04
    RESULT_REG = ADC_BASE + 0x04
    # FIFO control register offset is 0x08
    FCS_REG = ADC_BASE + 0x08
    # DIV register offset is 0x10
    DIV_REG = ADC_BASE + 0x10
    # FIFO register offset is 0x0C
    FIFO_REG = ADC_BASE + 0x0C

    # FIFO threshold of the ADC
    FIFO_THRESH = 1

    # ADC clock frequency, assumed to be 48MHz
    ADC_CLOCK_FREQ = 48_000_000

    def __init__(self, buf: bytearray, sample_rate: int = 1000, adc_id: int = 0) -> None:
        """
        Initialize an instance of the DMA_ADC_Transfer class.

        Args:
            buf (bytearray): Data buffer passed in by the user.
            sample_rate (int): Desired sample rate (Hz), default is 1000.
            adc_id (int): ADC ID number (0, 1 or 2), default is 0.

        Raises:
            TypeError: If buf is not of type bytearray.
            ValueError: If adc_id is not 0, 1 or 2, or the sample rate is out of range.
        """
        # Check whether buf is of type bytearray
        if not isinstance(buf, bytearray):
            raise TypeError("buf must be bytearray")

        # Check whether adc_id is 0, 1 or 2
        if adc_id not in (0, 1, 2):
            raise ValueError("adc_id must be 0, 1 or 2")

        # Buffer: the buffer passed in by the user
        self.buf = buf
        # Sample rate
        self.sample_rate = sample_rate
        # Create the ADC object
        self.adc = ADC(adc_id)
        # Create the DMA channel object
        self.dma = DMA()
        # Configure the ADC FIFO
        self.configure_adc_fifo()
        # Configure the ADC sample rate
        self.configure_adc_sample_rate(self.sample_rate)
        # Start free-running sampling mode
        self.start_adc_continuous()

    def configure_adc_fifo(self) -> None:
        """
        Configure the ADC FIFO to work with the DMA controller.
        By default the FIFO is right-shifted by 4 bits, so the ADC data is 8 bits wide with a maximum value of 255.

        Returns:
            None
        """
        # Enable the FIFO (FCS.EN), enable the DMA request signal (FCS.DREQ_EN), set the FIFO right shift (FCS.SHIFT)
        fcs_value = mem32[DMA_ADC_Transfer.FCS_REG]
        mem32[DMA_ADC_Transfer.FCS_REG] = fcs_value | (1 << 0) | (1 << 3) | (1 << 1)
        # Set the FIFO threshold (FCS.THRESH)
        mem32[DMA_ADC_Transfer.FCS_REG] |= (DMA_ADC_Transfer.FIFO_THRESH << 24)

    def start_adc_continuous(self) -> None:
        """
        Start free-running sampling mode by enabling the START_MANY bit.
        The ADC will automatically start new conversions at a fixed interval.

        Returns:
            None
        """
        # Read the current value of the CS register
        cs_value = mem32[DMA_ADC_Transfer.CS_REG]
        # Set the START_MANY bit to 1
        mem32[DMA_ADC_Transfer.CS_REG] = cs_value | (1 << 3)

    def configure_adc_sample_rate(self, sample_rate: int) -> None:
        """
        Configure the ADC sample rate.

        Args:
            sample_rate (int): Desired sample rate (Hz).

        Returns:
            None

        Raises:
            ValueError: If the sample rate is out of range.
        """
        # Make sure the sample rate is within a reasonable range
        if sample_rate <= 0 or sample_rate > 48_000_000:
            raise ValueError("sample rate out of range")

        # DMA is only fully effective at sample rates above 1000Hz
        # At sample rates below 1000Hz, a normal software timer is enough for sampling
        if sample_rate < 1000:
            raise ValueError("sample rate too low")

        # Calculate the divider value
        total_period = 48_000_000 / sample_rate
        int_part = int(total_period) - 1
        frac_part = int((total_period - int_part - 1) * 256)

        # Write the sampling period to the DIV register
        mem32[DMA_ADC_Transfer.DIV_REG] = (int_part << 8) | frac_part

    def stop_dma_adc_fifo(self) -> None:
        """
        Stop the DMA transfer and ADC conversion.

        Returns:
            None
        """
        # Clear the START_MANY bit in the CS register to stop ADC conversion
        # Read the CS register
        adc_cs_value = mem32[DMA_ADC_Transfer.CS_REG]
        # Clear the START_MANY bit
        adc_cs_value &= ~(1 << 3)
        # Write back to the CS register
        mem32[DMA_ADC_Transfer.CS_REG] = adc_cs_value

        # Poll the READY bit to make sure the last conversion has completed
        while not ((mem32[DMA_ADC_Transfer.CS_REG]>>8) & 0x1):
            pass

    def start_dma_transfer(self, wait_func: callable = None, complete_callback: callable = None, blocking: bool = True) -> None:
        """
        Start the DMA transfer.

        Args:
            wait_func (callable): Function called while waiting for the DMA transfer to complete, optional.
            complete_callback (callable): Callback function for DMA transfer completion, optional.
            blocking (bool): Whether to block until the transfer completes, default is True.

        Returns:
            None

        Raises:
            ValueError: If wait_func is passed in non-blocking mode.
        """

        # If non-blocking mode is selected, wait_func should not be passed in
        if blocking == False and wait_func is not None:
            raise ValueError("wait_func must be None when blocking is False")

        # If complete_callback is not None, run the user-defined function
        if complete_callback is not None:
            # Transfer-complete interrupt callback function
            self.dma.irq(handler=complete_callback, hard=True)

        # Set the DMA control register
        ctrl = self.dma.pack_ctrl(
            enable=True,                         # Enable DMA
            size=0,                              # Single transfer size is 8 bits, byte-by-byte transfer
            inc_read=False,                      # Read address does not increment
            inc_write=True,                      # Write address increments
            treq_sel=DMA_ADC_Transfer.DREQ_ADC,  # Select the DMA trigger source
            irq_quiet = False                    # Generate an interrupt at the end of each transfer
        )

        # Configure the DMA channel
        self.dma.config(
            read=self.FIFO_REG,         # Source address, i.e. the address of the ADC peripheral FIFO register
            write=addressof(self.buf),  # Destination address, i.e. the address of the data buffer
            count=len(self.buf),        # Total number of data transfers
            ctrl=ctrl,                  # DMA control register configuration
            trigger=False               # Do not trigger the DMA transfer immediately
        )

        # Start DMA transfer
        self.dma.active(1)

        # Blocking mode, wait for the DMA transfer to complete
        if blocking == True:
            # Wait for the DMA to finish
            while self.dma.active():
                # If wait_func is not None, run the user-defined function
                if wait_func is not None:
                    # Run the user-defined function
                    wait_func()
        else:
            # Non-blocking mode, do not wait for the DMA to finish
            return

    def close(self) -> None:
        """
        Close the DMA channel and stop the ADC.

        Returns:
            None
        """
        # Release the DMA channel
        self.dma.close()
        # Stop ADC conversion
        self.stop_dma_adc_fifo()

# ======================================== Initialization ==========================================

# ========================================  Main Program  ===========================================

Here, the process by which the DMA controller acquires ADC acquisition data by reading the ADC sample FIFO register is controlled by the ADC_DREQ system data request signal, and the configuration process is as follows:

  1. Enable FIFO (FCS.EN): The FIFO must be enabled to allow ADC conversion results to be written into it. By default, the FIFO is disabled to prevent accidental filling of the FIFO during single-shot conversion operations.
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Enable ADC DMA request (FCS.DREQ_EN): The ADC DMA request signal DREQ must be enabled so that the DMA can read data from the FIFO according to the request signal of the ADC
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Select the DREQ_ADC data request signal for the DMA channel: The DMA channel in use must select the DREQ_ADC data request signal to ensure that the DMA can operate in synchronization with the ADC's data request signal.
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Set the DREQ assertion threshold (FCS.THRESH): The DREQ assertion threshold should be set to 1, so that the DMA starts transmission as soon as there is one sample in the FIFO. Note that this is also the threshold for IRQ assertion, so in non-DMA usage scenarios, a higher value may be required to reduce the interrupt frequency.
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Configuration for 8-bit DMA transfer (FCS.SHIFT): If the DMA transfer size is set to 8 bits (i. e., data is transferred to a byte array in memory), FCS.SHIFT must be enabled to pre-shift the FIFO samples to the right to form one byte of data
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Configure ADC sampling rate (DIV): Before starting the ADC, the ADC sampling rate should be configured properly in advance
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Set the free sampling mode (CS.START_MANY): which means continuously performing ADC sampling
19 DMA Direct Memory Access - Document Tutorial Draft
  1. Start the DMA channel to initiate data transmission; after the DMA completes one round of data transfer, the ADC can be stopped or a new DMA transfer can be started immediately.
  2. Clear the CS.START_MANY data bit to stop the ADC, after which the software shall perform polling on the CS.READY data bit to ensure that the last conversion has been completed, and clear any excess sampling data in the FIFO
19 DMA Direct Memory Access - Document Tutorial Draft

In the custom DMA_ADC_Transfer class, the following methods are available:

19 DMA Direct Memory Access - Document Tutorial Draft

In the initialization method, we complete the relevant configuration of the ADC peripheral for DMA transfer:

# Custom ADC class that transfers data via DMA
class DMA_ADC_Transfer:
    """
    DMA_ADC_Transfer class, used for efficient ADC data transfer via DMA.
    This class encapsulates ADC configuration, DMA transfer, FIFO control and other functions, enabling high-speed sampling into a user-provided buffer.

    This class supports free-running sampling mode and a configurable ADC sample rate, and provides both blocking and non-blocking modes for DMA transfer.

    Attributes:
        buf (bytearray): Buffer used to store ADC sample data.
        sample_rate (int): Desired ADC sample rate (Hz).
        adc (ADC): ADC instance object, used for analog-to-digital conversion.
        dma (DMA): DMA controller instance object.

    Constants:
        DREQ_ADC (int): DMA trigger signal ID of the ADC.
        ADC_BASE (int): Base address of the ADC FIFO registers.
        CS_REG (int): Address offset of the control register (CS).
        RESULT_REG (int): Address offset of the result register (RESULT).
        FCS_REG (int): Address offset of the FIFO control register (FCS).
        DIV_REG (int): Address offset of the sample divider register (DIV).
        FIFO_REG (int): Address offset of the FIFO data register (FIFO).
        FIFO_THRESH (int): Threshold at which the ADC FIFO triggers a DMA transfer.
        ADC_CLOCK_FREQ (int): ADC clock frequency, assumed to be 48MHz.

    Methods:
        __init__(self, buf: bytearray, sample_rate: int = 1000, adc_id: int = 0):
            Initialize an instance of the DMA_ADC_Transfer class and configure the ADC and DMA.

        configure_adc_fifo(self) -> None:
            Configure the ADC FIFO so that it can work with DMA for data transfer.

        start_adc_continuous(self) -> None:
            Start the ADC free-running sampling mode so that it keeps acquiring data continuously.

        configure_adc_sample_rate(self, sample_rate: int) -> None:
            Configure the ADC sample rate and set the corresponding clock divider.

        stop_dma_adc_fifo(self) -> None:
            Stop the DMA transfer and ADC sampling, ensuring the sampling process ends safely.

        start_dma_transfer(self, wait_func: callable = None, complete_callback: callable = None, blocking: bool = True) -> None:
            Start the DMA transfer, with the option to block until it completes or to specify a transfer-complete callback.

        close(self) -> None:
            Shut down the DMA transfer and release the ADC resources.
    """

    # DMA trigger signal of the ADC
    DREQ_ADC = 36

    # Base address of the ADC FIFO registers
    ADC_BASE = 0x4004C000
    # CS register offset is 0x00
    CS_REG = ADC_BASE + 0x00
    # RESULT register offset is 0x04
    RESULT_REG = ADC_BASE + 0x04
    # FIFO control register offset is 0x08
    FCS_REG = ADC_BASE + 0x08
    # DIV register offset is 0x10
    DIV_REG = ADC_BASE + 0x10
    # FIFO register offset is 0x0C
    FIFO_REG = ADC_BASE + 0x0C

    # FIFO threshold of the ADC
    FIFO_THRESH = 1

    # ADC clock frequency, assumed to be 48MHz
    ADC_CLOCK_FREQ = 48_000_000

    def __init__(self, buf: bytearray, sample_rate: int = 1000, adc_id: int = 0) -> None:
        """
        Initialize an instance of the DMA_ADC_Transfer class.

        Args:
            buf (bytearray): Data buffer passed in by the user.
            sample_rate (int): Desired sample rate (Hz), default is 1000.
            adc_id (int): ADC ID number (0, 1 or 2), default is 0.

        Raises:
            TypeError: If buf is not of type bytearray.
            ValueError: If adc_id is not 0, 1 or 2, or the sample rate is out of range.
        """
        # Check whether buf is of type bytearray
        if not isinstance(buf, bytearray):
            raise TypeError("buf must be bytearray")

        # Check whether adc_id is 0, 1 or 2
        if adc_id not in (0, 1, 2):
            raise ValueError("adc_id must be 0, 1 or 2")

        # Buffer: the buffer passed in by the user
        self.buf = buf
        # Sample rate
        self.sample_rate = sample_rate
        # Create the ADC object
        self.adc = ADC(adc_id)
        # Create the DMA channel object
        self.dma = DMA()
        # Configure the ADC FIFO
        self.configure_adc_fifo()
        # Configure the ADC sample rate
        self.configure_adc_sample_rate(self.sample_rate)
        # Start free-running sampling mode
        self.start_adc_continuous()

In the initialization method, we mainly perform the following tasks:

19 DMA Direct Memory Access - Document Tutorial Draft
  1. Parameter check: Check buf whether it is of type bytearray, check whether adc_id is valid (0/1/2), check whether sample_rate is within the valid range (>1000Hz);
  2. Configure the FIFO and sampling rate of the ADC, and start the free sampling mode of the ADC: this is mainly implemented via the configure_adc_fifo method, the configure_adc_sample_rate method, the start_adc_continuous method, and the stop_dma_adc_fifo method.

Here, the configure_adc_fifo method, the configure_adc_sample_rate method, the start_adc_continuous method, and the stop_dma_adc_fifo method are mainly implemented by reading and writing the corresponding registers, and they primarily perform the following tasks:

The method for implementing data transmission via DMA is start_dma_transfer, and the sample code is as follows:

def start_dma_transfer(self, wait_func = None, complete_callback = None, blocking = True):
    """
    Start the DMA transfer
    :param wait_func: Function called while waiting for the DMA transfer to complete
    :param complete_callback: Callback function for DMA transfer completion
    :return: None
    """

    # If non-blocking mode is selected, wait_func should not be passed in
    if blocking == False and wait_func is not None:
        raise ValueError("wait_func must be None when blocking is False")

    # If complete_callback is not None, run the user-defined function
    if complete_callback is not None:
        # Transfer-complete interrupt callback function
        self.dma.irq(handler=complete_callback, hard=True)

    # Set the DMA control register
    ctrl = self.dma.pack_ctrl(
        enable=True,                         # Enable DMA
        size=0,                              # Single transfer size is 8 bits, byte-by-byte transfer
        inc_read=False,                      # Read address does not increment
        inc_write=True,                      # Write address increments
        treq_sel=DMA_ADC_Transfer.DREQ_ADC,  # Select the DMA trigger source
        irq_quiet = False                    # Generate an interrupt at the end of each transfer
    )

    # Configure the DMA channel
    self.dma.config(
        read=self.FIFO_REG,         # Source address, i.e. the address of the ADC peripheral FIFO register
        write=addressof(self.buf),  # Destination address, i.e. the address of the data buffer
        count=len(self.buf),        # Total number of data transfers
        ctrl=ctrl,                  # DMA control register configuration
        trigger=False               # Do not trigger the DMA transfer immediately
    )

    # Start DMA transfer
    self.dma.active(1)

    # Blocking mode, wait for the DMA transfer to complete
    if blocking == True:
        # Wait for the DMA to finish
        while self.dma.active():
            # If wait_func is not None, run the user-defined function
            if wait_func is not None:
                # Run the user-defined function
                wait_func()
    else:
        # Non-blocking mode, do not wait for the DMA to finish
        return

After mainly completing the configuration of the DMA control register and channels, it enables DMA transmission and executes the callback function input by the user after the transmission is completed:

19 DMA Direct Memory Access - Document Tutorial Draft
  1. First, perform parameter check:), and if wait_func is illegally passed in non-blocking mode (blocking= False), and if complete_callback is passed, register the DMA interrupt callback.
  2. Configure the DMA control register: enable the DMA channel, set to transmit 8-bit data in single transfer mode, fix the ADC FIFO address, enable auto-increment for the buffer address, use the ADC FIFO as the trigger source, and configure to generate an interrupt upon completion of each transfer.
  3. Set transmission parameters: set the DMA source address to FIFO_REG (the address of the ADC data register 0x4004C00C), set the write address to addressof (buf)(the physical address of the user buffer), set the total transmission count to the buffer length, and trigger the transmission manually.
  4. Determine whether it is in blocking mode: If it is in blocking mode and wait_func is passed in, then while the DMA transfer is not yet completed, execute wait_func, the user-defined callback function, in a loop.

3.3.3 Experimental Routines

The following code can be found in the elegance-devkit v1\Demo\68 DMA_PeripheralToMemory folder within the resource package we provide.

Test DMA_ADC_Transfer the code of the class is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/8 11:04 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : DMA class experiment, peripheral-to-memory transfer, DMA transfers data from the ADC peripheral FIFO to memory

# ======================================== Import Modules =========================================

# Import time-related modules
import time
# Import the custom ADC DMA class
from dma_adc_trans import DMA_ADC_Transfer
# Import the custom UART DMA transfer class
from dma_uart_tx import DMA_UART_Tx
# Import MicroPython-related modules
import micropython
# Import hardware-related modules
from machine import Timer

# ======================================== Global Variables ============================================

# Data buffer: 256 elements, each 8 bits (1 byte)
buf1 = bytearray(256)
# Second ADC data buffer
buf2 = bytearray(256)

# Run time of sending data over the serial port with DMA
uart_dma_time = 0
# Run time of the ADC data transfer using DMA
adc_dma_time = 0

# Flags indicating that the ADC DMA transfer of DMA_ADC_Transfer instance 1 and the UART DMA transfer have completed
dma_1_adc_complete_flag = False
# Flags indicating that the ADC DMA transfer of DMA_ADC_Transfer instance 2 and the UART DMA transfer have completed
dma_2_adc_complete_flag = False

# ======================================== Functions ============================================

def adc_wait_dma_complete() -> None:
    """
    Function called when the DMA transfer of the data in the ADC FIFO completes.

    Args:
        None

    Returns:
        None
    """

    # Print debug information
    print("DMA-ADC transmitting ADC data")

def adc_dma_complete_callback(d: object) -> None:
    """
    Called when the DMA transfer of ADC FIFO data is complete.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Print debug information
    print("DMA-ADC transfer complete")

def uart_dma_trans_buf1_isr(d: object) -> None:
    """
    Interrupt function called when the DMA transfer of ADC FIFO data is complete; schedules the corresponding callback function to run as soon as possible.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Schedule the callback function to run later
    micropython.schedule(uart_dma_trans_buf1, d)

def uart_dma_trans_buf1(d: object) -> None:
    """
    DMA transfer of serial port data, with buf1 as the read address.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Declare global variables
    global dma_uart, buf1, dma_1_adc_complete_flag

    # Wait until the ADC DMA transfer has completely finished
    while d.active():
        pass

    # Use DMA to transfer serial port data, with buf1 as the read address
    dma_uart.dma_transmit(buf=buf1, blocking=False)
    # Set the flag
    dma_1_adc_complete_flag = True

def uart_dma_trans_buf2_isr(d: object) -> None:
    """
    Interrupt function called when the DMA transfer of ADC FIFO data is complete; schedules the corresponding callback function to run as soon as possible.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Schedule the callback function to run later
    micropython.schedule(uart_dma_trans_buf2, d)

def uart_dma_trans_buf2(d: object) -> None:
    """
    DMA transfer of serial port data, with buf2 as the read address.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Declare global variables
    global dma_uart, buf2, dma_2_adc_complete_flag

    # Wait until the ADC DMA transfer has completely finished
    while d.active():
        pass

    # Use DMA to transfer serial port data, with buf2 as the read address
    dma_uart.dma_transmit(buf=buf2, blocking=False)
    # Set the flag
    dma_2_adc_complete_flag = True

# def dma_timer_check(timer: Timer) -> None:
#     """
#     Timer interrupt function for checking the DMA data transfer; checks whether the DMA transfer is complete,
#     and if so, starts the DMA transfer of the other buffer.
#
#     Args:
#         timer (machine.Timer): The timer instance that triggered the interrupt.
#
#     Returns:
#         None
#     """
#     global dma_adc_1, dma_adc_2, dma_1_adc_complete_flag, dma_2_adc_complete_flag
#
#     if dma_2_adc_complete_flag:
#         dma_adc_1.start_dma_transfer(blocking=False, complete_callback=uart_dma_trans_buf1_isr)
#         dma_2_adc_complete_flag = False
#
#     if dma_1_adc_complete_flag:
#         dma_adc_2.start_dma_transfer(blocking=False, complete_callback=uart_dma_trans_buf2_isr)
#         dma_1_adc_complete_flag = False

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information indicating the start of the main program
print("FreakStudio: DMA Peripheral to Memory Test")

# Initialize a DMA_ADC_Transfer class instance and pass in the data buffer
dma_adc = DMA_ADC_Transfer(buf = buf1, sample_rate = 2000, adc_id = 0)
# Instantiate the DMA_UART_Tx class, assuming UART0, baud rate 115200, TX pin 0, RX pin 1
dma_uart = DMA_UART_Tx(uart_num=0, baudrate=115200, tx_pin=0, rx_pin=1)

# ========================================  Main Program  ===========================================

# Record start time
start_time = time.ticks_us()
# Start the DMA transfer: blocking mode; debug information is printed while the transfer is incomplete, and also after the transfer completes
dma_adc.start_dma_transfer(wait_func = adc_wait_dma_complete,
                           complete_callback = adc_dma_complete_callback,
                           blocking = True)
# Record end time
end_time = time.ticks_us()

# Close the DMA channel and stop the ADC
dma_adc.close()

# Calculate the DMA data transfer time
adc_dma_time = time.ticks_diff(end_time, start_time) / 1000

# Print the DMA data transfer time
print("DMA run time: {:.2f} ms".format(adc_dma_time))

# Print debug information
print("FreakStudio: Start DMA UART transmit")

# Transmit data over the serial port using DMA
# Transfer data using blocking mode and record the run time
uart_dma_time = dma_uart.dma_transmit(buf=buf1,blocking=True) / 1000

# Print debug data to indicate the transfer is complete
print("DMA UART Finished,run time: {:.2f} ms".format(uart_dma_time))

# Initialize DMA_ADC_Transfer class instance 1 and pass in data buffer buf1
dma_adc_1 = DMA_ADC_Transfer(buf=buf1, sample_rate=2000, adc_id=0)
# Initialize DMA_ADC_Transfer class instance 2 and pass in data buffer buf2
dma_adc_2 = DMA_ADC_Transfer(buf=buf2, sample_rate=2000, adc_id=0)

# First start the DMA transfer of dma_adc_1: non-blocking mode
dma_adc_1.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf1_isr)

# # Initialize the software timer
# dma_check_timer = Timer(-1)
# # Use the timer to check the DMA transfer flag every 10ms
# dma_check_timer.init(period=10, mode=Timer.PERIODIC, callback=dma_timer_check)

# Poll to enable double-buffered uninterrupted data acquisition and transfer
while True:
    # Record start time
    start_time = time.ticks_us()

    # Check whether the DMA transfer of DMA_ADC_Transfer class instance 2 is complete
    if dma_2_adc_complete_flag == True:
        # Start the DMA transfer: non-blocking mode
        dma_adc_1.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf1_isr)
        # Do not set the flag
        dma_2_adc_complete_flag = False

    # Check whether the DMA transfer of DMA_ADC_Transfer class instance 1 is complete
    if dma_1_adc_complete_flag == True:
        # Start the DMA transfer: non-blocking mode
        dma_adc_2.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf2_isr)
        # Do not set the flag
        dma_1_adc_complete_flag = False

    # Record end time
    end_time = time.ticks_us()
    # Calculate the time taken by the two DMA data transfers
    dma_time = time.ticks_diff(end_time, start_time) / 1000
    # Print debug data
    print("DMA ADC run time: {:.2f} ms".format(dma_time))

In the routine above, we perform the following operations:

  1. First, run in blocking mode dma_adc.start_dma_transfer (), wait for the transfer to complete, then calculate the ADC DMA running time and print it out.
  2. Then call dma_uart.dma_transmit (buf1, blocking= True) to send the data in buf1 in blocking mode, calculate the running time of UART DMA and print it out.
  3. To perform double-buffered DMA sampling and transmission, first create two ADC DMA transfer instances dma_adc_1 and dma_adc_2, which use buf1 and buf2 respectively. Start dma_adc_1 first for ADC sampling, and set uart_dma_trans_buf1_isr as the callback function.
  4. Polling in the main loop:
    • If dma_adc_2 transmission is completed, start dma_adc_1 and clear the flag bit.
    • If dma_adc_1 transfer is completed, start dma_adc_2 and clear the flag bit.

The overall Sequence Diagram of the above routine is shown below:

19 DMA Direct Memory Access - Document Tutorial Draft

The core process of the above routine mainly implements the use of DMA to transfer data from the ADC peripheral to the memory, and uses another DMA channel to send the data out via the serial port; meanwhile, we utilize the double buffering mechanism to realize continuous Data Acquisition and transmission.

When the sampling rate is set to 2000 Hz, the UART baud rate to 115200, and the number of bytes to be transmitted to 256, the UART DMA transmission time is approximately 19 ms, while the ADC DMA transmission time is 124 ms. Therefore, we can define two buffers (buf1 and buf2) to alternately store the data transmitted via ADC DMA, and in the gap between the DMA writing operations to the two buffers, initiate UART DMA to transmit the data in the already filled buffer and send it to the computer.In this way, while the first buffer (buf1) is undergoing data processing (e. g., being sent to the serial port via DMA), the second buffer (buf2) continues with new Data Acquisition. This avoids conflicts between Data Acquisition and data processing, reduces waiting time and data processing latency, and improves the efficiency of Data Acquisition and transmission.

19 DMA Direct Memory Access - Document Tutorial Draft

Here, we first initialize two buffers:

# Data buffer: 256 elements, each 8 bits (1 byte)
buf1 = bytearray(256)
# Second ADC data buffer
buf2 = bytearray(256)

Then create two DMA_ADC_Transfer instances:

# Initialize DMA_ADC_Transfer class instance 1 and pass in data buffer buf1
dma_adc_1 = DMA_ADC_Transfer(buf=buf1, sample_rate=2000, adc_id=0)
# Initialize DMA_ADC_Transfer class instance 2 and pass in data buffer buf2
dma_adc_2 = DMA_ADC_Transfer(buf=buf2, sample_rate=2000, adc_id=0)

Among them, dma_adc_1 is used to transfer ADC data to buf1, and dma_adc_2 is used to transfer ADC data to buf2.

Then start the DMA transfer and set the callback, taking dma_adc_1 as an example:

# First start the DMA transfer of dma_adc_1: non-blocking mode
dma_adc_1.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf1_isr)

Start dma_adc_1 DMA transfer, buf1 is used to store ADC data. uart_dma_trans_buf1_isr is the interrupt service routine (ISR) after the transfer is completed, which schedules subsequent data transfer operations and sets the DMA transfer completion flag after the transfer is finished:

def uart_dma_trans_buf1_isr(d: object) -> None:
    """
    Interrupt function called when the DMA transfer of ADC FIFO data is complete; schedules the corresponding callback function to run as soon as possible.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Schedule the callback function to run later
    micropython.schedule(uart_dma_trans_buf1, d)

def uart_dma_trans_buf1(d: object) -> None:
    """
    DMA transfer of serial port data, with buf1 as the read address.

    Args:
        d (object): The DMA channel instance in use.

    Returns:
        None
    """

    # Declare global variables
    global dma_uart, buf1, dma_1_adc_complete_flag

    # Wait until the ADC DMA transfer has completely finished
    while d.active():
        pass

    # Use DMA to transfer serial port data, with buf1 as the read address
    dma_uart.dma_transmit(buf=buf1, blocking=False)
    # Set the flag
    dma_1_adc_complete_flag = True

In the loop of the main program, by checking the dma_2_adc_complete_flag and dma_1_adc_complete_flag flag bits to determine whether to start a new DMA transfer:

# Poll to enable double-buffered uninterrupted data acquisition and transfer
while True:
    # Record start time
    start_time = time.ticks_us()

    # Check whether the DMA transfer of DMA_ADC_Transfer class instance 2 is complete
    if dma_2_adc_complete_flag == True:
        # Start the DMA transfer: non-blocking mode
        dma_adc_1.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf1_isr)
        # Do not set the flag
        dma_2_adc_complete_flag = False

    # Check whether the DMA transfer of DMA_ADC_Transfer class instance 1 is complete
    if dma_1_adc_complete_flag == True:
        # Start the DMA transfer: non-blocking mode
        dma_adc_2.start_dma_transfer(blocking=False,complete_callback = uart_dma_trans_buf2_isr)
        # Do not set the flag
        dma_1_adc_complete_flag = False

    # Record end time
    end_time = time.ticks_us()
    # Calculate the time taken by the two DMA data transfers
    dma_time = time.ticks_diff(end_time, start_time) / 1000
    # Print debug data
    print("DMA ADC run time: {:.2f} ms".format(dma_time))

We can also place the polling flag bit in a timer for execution, so as to reduce the occupation of CPU resources:

def dma_timer_check(timer: Timer) -> None:
    """
    Timer interrupt function for checking the DMA data transfer; checks whether the DMA transfer is complete,
    and if so, starts the DMA transfer of the other buffer.

    Args:
        timer (machine.Timer): The timer instance that triggered the interrupt.

    Returns:
        None
    """
    global dma_adc_1, dma_adc_2, dma_1_adc_complete_flag, dma_2_adc_complete_flag

    if dma_2_adc_complete_flag:
        dma_adc_1.start_dma_transfer(blocking=False, complete_callback=uart_dma_trans_buf1_isr)
        dma_2_adc_complete_flag = False

    if dma_1_adc_complete_flag:
        dma_adc_2.start_dma_transfer(blocking=False, complete_callback=uart_dma_trans_buf2_isr)
        dma_1_adc_complete_flag = False
        
# Initialize the software timer
dma_check_timer = Timer(-1)
# Set the timer to trigger the dma_timer_check function every 10ms
dma_check_timer.init(period=10, mode=Timer.PERIODIC, callback=dma_timer_check)

Next, we open the SerialPlot software and select the port corresponding to the serial port of the Raspberry Pi Pico:

19 DMA Direct Memory Access - Document Tutorial Draft

The data format is set as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

Burn the program, connect to the remote terminal, and the output is as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

It can be seen that when DMA and the double buffer mechanism are used to realize the transmission of ADC data through the serial port, the CPU consumes very little time, only about 0.05ms.

SerialPlot The software interface is shown below, with the data update rate at this moment displayed in the lower right corner, which can be seen to be around 2000Hz:

19 DMA Direct Memory Access - Document Tutorial Draft

3.3.3 Application Experiment.mp4 27.3 MB

Here, when the baud rate is set to 921600 and the sampling rate is set to 45K Hz, the actually tested rate of ADC acquisition and serial port data transmission is about 40K Hz, which is mainly due to the certain delay in the DMA transmission and serial port transmission process:

19 DMA Direct Memory Access - Document Tutorial Draft

3.3.3 Application Experiment - Increased Rate.mp4 7.8 MB

If a higher data transmission rate is required, we can increase the sampling rate and serial port baud rate of ADC, and expand the buffer size. A larger buffer may lead to a lower frequency of data processing, since more data can be processed in a single operation, which helps reduce the overhead of data processing; for applications that demand high data throughput, a larger buffer can better support efficient data transmission.

3.4 DMA implements chained triggering

In the following code, we implement the operation of splicing multiple strings into a single memory buffer through the DMA transfer mechanism (chained triggering and write trigger registers), namely Scatter-gather data aggregation operation, which aggregates multiple fixed-size memory blocks into one Memory Space.

The following code can be found in the material package we provide, under the elegance-devkit v1\Demo\69 DMA_ChainTrigger folder.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/9/8 11:04 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : DMA class experiment, peripheral-to-memory transfer, DMA transfers data from the ADC peripheral FIFO to memory

# ======================================== Import Modules =========================================

# Import time-related modules
import time
# Import the addressof function, used to get the memory address of data
from uctypes import addressof
# Import DMA-related modules
from rp2 import DMA
# Import array-related modules
from array import array

# ======================================== Global Variables ============================================

# Define the list of strings to be concatenated
input = ["FreakStudio", ":", "test", " of the scatter", " gather", " process"]
# Create a 64-byte destination buffer (bytearray) to store the concatenated string
output = bytearray(64)

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

def gather_strings(string_list: list, buf: bytearray) -> None:
    """
    Use DMA to concatenate the strings in a string list and store the result in the destination buffer.
    Implemented through the cooperation of two DMA channels:
    1. gather_dma channel: transfers string metadata (length + address)
    2. buffer_dma channel: moves the actual data to the destination buffer

    Args:
        string_list (list): The list of strings to concatenate; elements should be MicroPython string type
        buf (bytearray): The destination buffer; sufficient space must be pre-allocated

    Returns:
        None

    Raises:
        ValueError: If the input parameter types do not meet the requirements
        RuntimeError: If an error occurs during the DMA transfer
    """

    # Declare two DMA channels: gather_dma and buffer_dma
    # gather_dma DMA channel, used to handle string length and address information
    gather_dma = DMA()
    # buffer_dma DMA channel, used to handle the actual data copying
    buffer_dma = DMA()

    # Declare an integer array to store the string lengths and memory addresses
    gather_list = array("I")

    # Data is stored in order: string length, string address
    for s in string_list:
        # Add the string length
        gather_list.append(len(s))
        # Add the string's memory address
        gather_list.append(addressof(s))

    # Print the contents of gather_list
    # gather_list:  array('I', [11, 536906720, 1, 536904296, 4, 536904298, 15, 536906752, 7, 536904303, 8, 536904311])
    print("gather_list: ", gather_list)

    # To mark the end of the list (terminated by 0), add two 0s at the end of the list
    # Implement a null trigger, i.e. an operation that writes an all-zero value to the trigger register
    gather_list.append(0)
    gather_list.append(0)

    # Configure the gather_dma transfer control register
    # ring_size is set to 3, meaning 8-byte alignment; enable the register ring buffer
    gather_ctrl = gather_dma.pack_ctrl(ring_size=3, ring_sel=True)
    # Configure the gather_dma channel; the write addresses are the TRANS_COUNT register and the READ_ADD_TRIG register, located at the last register alias
    # i.e. registers 14 and 15
    gather_dma.config(
        read=gather_list,                   # Read the gather_list array
        write=buffer_dma.registers[14:16],  # Write the data to the buffer_dma registers:
        count=2,                            # Transfer two bytes
        ctrl=gather_ctrl                    # Transfer control register settings
    )

    # Print the parameters in the gather_dma transfer control register:
    # gather_ctrl: {'inc_read': 1, 'high_pri': 0, 'write_err': 0, 'ring_sel': 1,
    # 'enable': 1, 'treq_sel': 63, 'sniff_en': 0, 'irq_quiet': 1, 'read_err': 0,
    # 'chain_to': 0, 'busy': 0, 'inc_write': 1, 'ring_size': 3, 'bswap': 0, 'size': 2, 'ahb_err': 0}
    print("gather_ctrl:",gather_dma.unpack_ctrl(gather_ctrl))

    # Set the buffer_dma transfer control register: single-byte transfer, and configure chained transfer
    # When buffer_dma completes, it starts gather_dma for the next transfer
    buffer_ctrl = buffer_dma.pack_ctrl(size=0, chain_to=gather_dma.channel)
    # Set the destination buffer buf as the write target of buffer_dma; the actual string data will be written into buf through this DMA channel
    buffer_dma.config(write=buf, ctrl=buffer_ctrl)

    # Start the DMA transfer of gather_dma
    gather_dma.active(1)

    # Calculate the last address of gather_list
    end_address = addressof(gather_list) + 4 * len(gather_list)

    # Continuously check whether gather_dma has completed the transfer
    while gather_dma.read != end_address:
        pass

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information indicating the start of the main program
print("FreakStudio: DMA Chaining Triggers Test")

# ========================================  Main Program  ===========================================

# Print the initial data of the destination buffer
print(output)
# Use DMA to store the strings in the string list input into the buffer array output
gather_strings(input, output)
# Print the final data of the destination buffer
print(output)

Here, the core method for implementing the aggregation operation is gather_strings function, to which we need to pass two parameters: the list of strings to be concatenated and the target buffer for storing the concatenated result.

First, we created two DMA channel objects, gather_dma and buffer_dma, which are used to handle different tasks respectively:

Next, we define a gather_list integer array, which is used to store the length and memory address of each string; we use addressof (s) to obtain the address of the string s in memory.

Next, we configure the first DMA channel (gather_dma), for which we use the gather_dma.pack_ctrl statement to create a DMA control block, and configure the ring buffer mode of DMA. The ring buffer configuration allows gather_dma to automatically reset the address to the initial position after completing one transfer of string length and address. The explanation of the specific configuration here is as follows:

Here, we use the following command to view gather_dma the complete configuration of the control register of the channel:

print("gather_ctrl:",gather_dma.unpack_ctrl(gather_ctrl))
19 DMA Direct Memory Access - Document Tutorial Draft

As can be seen, the setting of inc_read= True ensures that gather_dma increments the read address to the address corresponding to the next string after each transmission is completed;that is to say, after processing the length and address of one string, the read operation will move to the address of the next string instead of returning to the original position;inc_write= True Allows the write operation to automatically increment the write address while transferring the string content to the target buffer, so that each transferred string is sequentially placed into the target buffer to avoid overwriting previous data. It should also be noted that ring_size= 3 the write operation will automatically wrap back to the initial address once the address exceeding 8 bytes is exceeded.

Next, we configured the gather_dma channel:

19 DMA Direct Memory Access - Document Tutorial Draft

which is the trigger register that controls buffer_dma the number of transmissions of the channel and the target read address;after writing to this register, it will also start the buffer_dma channel to initiate data transmission of a single string in the string list to the target buffer.

Similarly, we configure the second DMA channel (buffer_dma) and use the statement buffer_dma.pack_ctrl (size= 0, chain_to= gather_dma.channel) to configure the DMA control block:

Then configure buffer_dma to write data to the target buffer buf, and use the previously created control block buffer_ctrl.

The detailed Sequence Diagram of the above chained trigger is shown below:

19 DMA Direct Memory Access - Document Tutorial Draft

In the process of actual data transmission:

19 DMA Direct Memory Access - Document Tutorial Draft
  1. Initial Trigger: We first start the gather_dma channel to begin processing the metadata of the first string. gather_dma reads gather_list to obtain len1 and addr1, then writes them to the registers of buffer_dma; writing to the READ_ADDR_TRIG register will trigger buffer_dma to start.
  2. metadata transfer: gather_dma After the channel writes data to the buffer_dma channel, it triggers the channel to start data transmission. buffer_dma copies len1 bytes of data from the source string at address addr1 to the target buffer buf according to the received address and length.
  3. Chained triggering: buffer_dma will automatically trigger gather_dma to transmit the length and address of the next string after completing one data transfer. This type of transfer is chained, that is, after buffer_dma finishes transmitting a segment of string, gather_dma will subsequently transmit the length and address of the next string, and it is determined via gather_dma.read whether gather_dma has completed the transmission of all lengths and addresses.
  4. Loop processing: The above process loops continuously until all strings in gather_list have been completely processed.

Burn the code, connect to the remote terminal, and the output is as follows:

19 DMA Direct Memory Access - Document Tutorial Draft

3.4 DMA Chained Trigger.mp4 1.8 MB

It can be seen that when buffer_dma completes the data transmission of one string, it will automatically trigger gather_dma to continue reading the length and address of the next string, which avoids the CPU from intervening in each transmission and greatly improves the efficiency.

References

https://www.spiceworks.com/tech/hardware/articles/direct-memory-access/

https://www.baeldung.com/cs/dma-controllers

https://www.embedded.com/introduction-to-direct-memory-access/

https://docs.micropython.org/en/latest/library/rp2.DMA.html

https://en.wikipedia.org/wiki/Direct_memory_access

https://www.techopedia.com/definition/2767/direct-memory-access-dma

https://www.taterli.com/7524

https://blog.adafruit.com/2023/01/24/

Version History

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/19

Initialize the document, based on MicroPython version v1.23.0.

v1.0.1

Li Zisheng

2025/12/24

Optimized part of the principle explanations, based on MicroPython v1.23.0.