STM32F767 DMA的基本用法

本文介绍STM32F767 DMA(Direct memory access controller)的基本用法。

开发环境

硬件环境

  • 电脑:Windows 10 Home x64
  • Apollo STM32F767开发板(ST-LINK V2仿真器)

软件环境

  • Keil Version 5.24.1 (Pack Installer:Keil.STM32F7xx_DFP.2.9.0.pack)
  • STM32CubeMX Version 4.25.0(Packages Manager:STM32CubeF7)

DMA的基本特性

 直接存储器访问 (DMA) 用于在外设与存储器之间以及存储器与存储器之间提供高速数据传输。可以在无需任何 CPU 操作的情况下通过 DMA 快速移动数据。这样节省的 CPU 资源可供其它操作使用。

 两个 DMA 控制器总共有 16 个数据流(每个控制器 8 个),每一个 DMA 控制器都用于管理一个或多个外设的存储器访问请求。每个数据流总共可以有多达 8 个通道(或称请求)。每个通道都有一个仲裁器,用于处理 DMA 请求间的优先级。

系统框图

 DMA的系统框图如下所示。

主要特性

 DMA的特性较为复杂,重点如下:

  • STM32F767具有2个DMA控制器;
  • 每个 DMA 控制器有 8 个数据流,每个数据流有多达 8 个通道(或称请求);
  • 每个数据流有4级32位先进先出FIFO;
  • 通过硬件可以将每个数据流配置为:支持外设到存储器、存储器到外设和存储器到存储器传输的常规通道;在存储器端支持双缓冲的双缓冲区通道;
  • DMA 数据流请求之间的优先级可用软件编程(4 个级别:非常高、高、中、低);
  • 可供每个数据流选择的通道请求多达 8 个;
  • 要传输的数据项的数目可以由 DMA 控制器或外设管理;
  • DMA 流控制器:要传输的数据项的数目可用软件编程,从 1 至 65535;
  • 对源和目标的增量或非增量寻址;
  • 5 个事件标志(DMA 半传输、DMA 传输完成、DMA 传输错误、DMA FIFO 错误、直接模式错误),进行逻辑或运算,从而产生每个数据流的单个中断请求。

DMA通道选择

 DMA中每一个数据流均有一个DMA请求。DMA请求映射的列表如下所示。

DMA的基本设置

 DMA的具体应用方式很多,本文以用DMA实现UART1数据发送为例讲解DMA的用法。

DMA通道选择

USART1_TX请求位于DMA2的数据流7通道4

DMA时钟与NVIC初始化

 初始化代码如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Enable DMA controller clock
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA2_CLK_ENABLE();
/* DMA interrupt init */
/* DMA2_Stream7_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA2_Stream7_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA2_Stream7_IRQn);
}

 代码的主要功能为:

  • 使能DMA2时钟;
  • 设定DMA2数据流7的NVIC优先级并使能;DMA中断优先级需要根据系统整体进行确定,本处设置只是示例。

UART初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* USART1 init function */
void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspInit 0 */
/* USER CODE END USART1_MspInit 0 */
/* USART1 clock enable */
__HAL_RCC_USART1_CLK_ENABLE();
/**USART1 GPIO Configuration
PA9 ------> USART1_TX
PA10 ------> USART1_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USART1 DMA Init */
/* USART1_TX Init */
hdma_usart1_tx.Instance = DMA2_Stream7;
hdma_usart1_tx.Init.Channel = DMA_CHANNEL_4;
hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart1_tx.Init.Mode = DMA_NORMAL;
hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart1_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
__HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx);
/* USART1 interrupt Init */
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspInit 1 */
/* USER CODE END USART1_MspInit 1 */
}
}

 UART的初始化串口部分之前已经介绍过,这里不再复述,DMA相关部分功能如下:

  • 初始化实例选择为DMA2数据流7,通道4;
  • 方向为:存储器到外设;
  • DMA外设:非增量模式;
  • 存储器外设:增量模式;
  • 外设数据对齐:byte,即为8bit;
  • 存储器数据对齐:byte,即为8bit;
  • DMA模式:normal;
  • DMA优先级:低;
  • DMA FIFO模式:禁用;
  • 通过HAL_DMA_Init()函数初始化DMA;
  • 通过__HAL_LINKDMA()函数建立huart1hdma_usart1_tx关联;
  • 设置USART1 NVIC优先级并使能中断。

HAL_DMA_Init()实现

 以上设置通过HAL_DMA_Init()函数实现,该函数具体如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* @brief Initialize the DMA according to the specified
* parameters in the DMA_InitTypeDef and create the associated handle.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
{
uint32_t tmp = 0U;
uint32_t tickstart = HAL_GetTick();
DMA_Base_Registers *regs;
/* Check the DMA peripheral state */
if(hdma == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_DMA_STREAM_ALL_INSTANCE(hdma->Instance));
assert_param(IS_DMA_CHANNEL(hdma->Init.Channel));
assert_param(IS_DMA_DIRECTION(hdma->Init.Direction));
assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc));
assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc));
assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment));
assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment));
assert_param(IS_DMA_MODE(hdma->Init.Mode));
assert_param(IS_DMA_PRIORITY(hdma->Init.Priority));
assert_param(IS_DMA_FIFO_MODE_STATE(hdma->Init.FIFOMode));
/* Check the memory burst, peripheral burst and FIFO threshold parameters only
when FIFO mode is enabled */
if(hdma->Init.FIFOMode != DMA_FIFOMODE_DISABLE)
{
assert_param(IS_DMA_FIFO_THRESHOLD(hdma->Init.FIFOThreshold));
assert_param(IS_DMA_MEMORY_BURST(hdma->Init.MemBurst));
assert_param(IS_DMA_PERIPHERAL_BURST(hdma->Init.PeriphBurst));
}
/* Allocate lock resource */
__HAL_UNLOCK(hdma);
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Disable the peripheral */
__HAL_DMA_DISABLE(hdma);
/* Check if the DMA Stream is effectively disabled */
while((hdma->Instance->CR & DMA_SxCR_EN) != RESET)
{
/* Check for the Timeout */
if((HAL_GetTick() - tickstart ) > HAL_TIMEOUT_DMA_ABORT)
{
/* Update error code */
hdma->ErrorCode = HAL_DMA_ERROR_TIMEOUT;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
/* Get the CR register value */
tmp = hdma->Instance->CR;
/* Clear CHSEL, MBURST, PBURST, PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR, CT and DBM bits */
tmp &= ((uint32_t)~(DMA_SxCR_CHSEL | DMA_SxCR_MBURST | DMA_SxCR_PBURST | \
DMA_SxCR_PL | DMA_SxCR_MSIZE | DMA_SxCR_PSIZE | \
DMA_SxCR_MINC | DMA_SxCR_PINC | DMA_SxCR_CIRC | \
DMA_SxCR_DIR | DMA_SxCR_CT | DMA_SxCR_DBM));
/* Prepare the DMA Stream configuration */
tmp |= hdma->Init.Channel | hdma->Init.Direction |
hdma->Init.PeriphInc | hdma->Init.MemInc |
hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment |
hdma->Init.Mode | hdma->Init.Priority;
/* the Memory burst and peripheral burst are not used when the FIFO is disabled */
if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
{
/* Get memory burst and peripheral burst */
tmp |= hdma->Init.MemBurst | hdma->Init.PeriphBurst;
}
/* Write to DMA Stream CR register */
hdma->Instance->CR = tmp;
/* Get the FCR register value */
tmp = hdma->Instance->FCR;
/* Clear Direct mode and FIFO threshold bits */
tmp &= (uint32_t)~(DMA_SxFCR_DMDIS | DMA_SxFCR_FTH);
/* Prepare the DMA Stream FIFO configuration */
tmp |= hdma->Init.FIFOMode;
/* The FIFO threshold is not used when the FIFO mode is disabled */
if(hdma->Init.FIFOMode == DMA_FIFOMODE_ENABLE)
{
/* Get the FIFO threshold */
tmp |= hdma->Init.FIFOThreshold;
/* Check compatibility between FIFO threshold level and size of the memory burst */
/* for INCR4, INCR8, INCR16 bursts */
if (hdma->Init.MemBurst != DMA_MBURST_SINGLE)
{
if (DMA_CheckFifoParam(hdma) != HAL_OK)
{
/* Update error code */
hdma->ErrorCode = HAL_DMA_ERROR_PARAM;
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY;
return HAL_ERROR;
}
}
}
/* Write to DMA Stream FCR */
hdma->Instance->FCR = tmp;
/* Initialize StreamBaseAddress and StreamIndex parameters to be used to calculate
DMA steam Base Address needed by HAL_DMA_IRQHandler() and HAL_DMA_PollForTransfer() */
regs = (DMA_Base_Registers *)DMA_CalcBaseAndBitshift(hdma);
/* Clear all interrupt flags */
regs->IFCR = 0x3FU << hdma->StreamIndex;
/* Initialize the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
/* Initialize the DMA state */
hdma->State = HAL_DMA_STATE_READY;
return HAL_OK;
}

 该函数的主要功能有:

  • 通过DMA配置寄存器DMA_SxCR EN位复位禁止数据流,并等待确认数据流已关闭;
  • tmp首先读取DMA_SxCR寄存器的值,同时复位所有需要配置的控制位;
  • tmp中写入CHSEL、DIR、PINC、MINC、PSIZE、MINC、CIRC、PFCTRL、PL等配置位;
  • 将tmp值写入到DMA_SxCR寄存器;
  • tmp读取FIFO控制寄存器DMA_SxFCR的值,复位直接模式禁止位DMDIS与FIFO阈值选择位FTH;
  • tmp写入FIFO模式位,本例中使用直接模式,禁用FIFO;
  • 将tmp值写入到DMA_SxFCR寄存器;
  • 通过DMA_HIFCR/DMA_LIFCR寄存器清除DMA所有中断标志位;
  • 至此,完成DMA初始化。

源代码中通过0x3F清除中断标志位可能存在问题,DMA_HIFCR/DMA_LIFCR寄存器中断清除标志位仅有5个,此处我认为写入0x3D才是合理值。

ST官方回复:这个预留位,软件上写0/写1对它没有影响,这个预留动作时靠硬件保证的。

__HAL_LINKDMA()实现

 该函数具体如下。

1
2
3
4
5
6
7
__HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx);
#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \
do{ \
(__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \
(__DMA_HANDLE__).Parent = (__HANDLE__); \
} while(0)

 该函数的功能如下:

  • __HAL_LINKDMA()传入的参数为huart1hdmatx代表huart1结构体UART_HandleTypeDef定义中的具体成员变量,即将hdma_usart1_tx作为huart1hdmatx成员变量;同时huart1作为hdma_usart1_txParent成员变量。

基于DMA的UART发送实现

HAL_UART_Transmit_DMA()实现

 DMA设置完成后,即可基于DMA进行UART发送,具体通过HAL_UART_Transmit_DMA()函数实现,使用方法如下。

1
2
uint8 sendStr[65535] = "1234567890";
HAL_UART_Transmit_DMA(&huart1,sendStr,sizeof(sendStr));

HAL_UART_Transmit_DMA()函数的定义如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* @brief Send an amount of data in DMA mode.
* @param huart UART handle.
* @param pData pointer to data buffer.
* @param Size amount of data to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
/* Check that a Tx process is not already ongoing */
if(huart->gState == HAL_UART_STATE_READY)
{
if((pData == NULL ) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pTxBuffPtr = pData;
huart->TxXferSize = Size;
huart->TxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_BUSY_TX;
/* Set the UART DMA transfer complete callback */
huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt;
/* Set the UART DMA Half transfer complete callback */
huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt;
/* Set the DMA error callback */
huart->hdmatx->XferErrorCallback = UART_DMAError;
/* Set the DMA abort callback */
huart->hdmatx->XferAbortCallback = NULL;
/* Enable the UART transmit DMA channel */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->TDR, Size);
/* Clear the TC flag in the SR register by writing 0 to it */
__HAL_UART_CLEAR_IT(huart, UART_FLAG_TC);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
SET_BIT(huart->Instance->CR3, USART_CR3_DMAT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}

 该函数实现的功能为:

  • huart1的成员变量pTxBuffPtr为发送数据buffer指针,将其指向待发送数据;
  • huart1的成员变量TxXferSize代表发送数据数目,成员变量TxXferCount代表发送数据计数器,初始值都将其设置为待发送数据个数;
  • huart1的成员变量hdmatx也为一个结构体,其成员变量为DMA相关中断的函数指针:XferCpltCallback为DMA传输完成回调函数,XferHalfCpltCallback为DMA半传输完成回调函数,XferErrorCallback为DMA故障回调函数,XferAbortCallback为DMA中止回调函数;
  • 通过HAL_DMA_Start_IT()使能DMA发送通道;
  • 清除UART发送完成中断标志位TC;
  • 置位USARTx_CR3寄存器DMAT位,使能DMA发送模式。

 执行该函数后,UART将基于DMA模式进行发送。

HAL_DMA_Start_IT()实现

HAL_UART_Transmit_DMA()中调用的核心函数HAL_DMA_Start_IT()实现如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* @brief Start the DMA Transfer with interrupt enabled.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress The source memory Buffer address
* @param DstAddress The destination memory Buffer address
* @param DataLength The length of data to be transferred from source to destination
* @retval HAL status
*/
HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
HAL_StatusTypeDef status = HAL_OK;
/* calculate DMA base and stream number */
DMA_Base_Registers *regs = (DMA_Base_Registers *)hdma->StreamBaseAddress;
/* Check the parameters */
assert_param(IS_DMA_BUFFER_SIZE(DataLength));
/* Process locked */
__HAL_LOCK(hdma);
if(HAL_DMA_STATE_READY == hdma->State)
{
/* Change DMA peripheral state */
hdma->State = HAL_DMA_STATE_BUSY;
/* Initialize the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
/* Configure the source, destination address and the data length */
DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
/* Clear all interrupt flags at correct offset within the register */
regs->IFCR = 0x3FU << hdma->StreamIndex;
/* Enable Common interrupts*/
hdma->Instance->CR |= DMA_IT_TC | DMA_IT_TE | DMA_IT_DME;
hdma->Instance->FCR |= DMA_IT_FE;
if(hdma->XferHalfCpltCallback != NULL)
{
hdma->Instance->CR |= DMA_IT_HT;
}
/* Enable the Peripheral */
__HAL_DMA_ENABLE(hdma);
}
else
{
/* Process unlocked */
__HAL_UNLOCK(hdma);
/* Return error status */
status = HAL_BUSY;
}
return status;
}
/**
* @brief Sets the DMA Transfer parameter.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @param SrcAddress The source memory Buffer address
* @param DstAddress The destination memory Buffer address
* @param DataLength The length of data to be transferred from source to destination
* @retval HAL status
*/
static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
{
/* Clear DBM bit */
hdma->Instance->CR &= (uint32_t)(~DMA_SxCR_DBM);
/* Configure DMA Stream data length */
hdma->Instance->NDTR = DataLength;
/* Memory to Peripheral */
if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
{
/* Configure DMA Stream destination address */
hdma->Instance->PAR = DstAddress;
/* Configure DMA Stream source address */
hdma->Instance->M0AR = SrcAddress;
}
/* Peripheral to Memory */
else
{
/* Configure DMA Stream source address */
hdma->Instance->PAR = SrcAddress;
/* Configure DMA Stream destination address */
hdma->Instance->M0AR = DstAddress;
}
}
/**
* @brief Enable the specified DMA Stream.
* @param __HANDLE__ DMA handle
* @retval None
*/
#define __HAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= DMA_SxCR_EN)

 该函数实现的功能为:

  • 检查DMA发送数据长度是否合理,在1~65535范围内均可;
  • 通过DMA_SetConfig()函数设置DMA发送的DMA数据流数据项数目,设置外设地址为目标地址,设置存储器地址为源地址;
  • 清空DMA数据流相关中断标志位;
  • 置位DMA配置寄存器DMA_SxCR TCIE、TEIE、DMEIE位,分别使能传输完成中断、传输错误中断与直接模式错误中断;
  • 置位DMA FIFO控制寄存器FEIE位,使能FIFO错误中断;本例中未使能FIFO;
  • XferHalfCpltCallback为DMA半传输完成回调函数,其不为NULL时使能DMA半传输完成中断;
  • 置位DMA_SxCR寄存器EN位,使能DMA数据流,随即开始DMA传输。

DMA中断服务函数

 DMA中断服务函数如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/**
* @brief This function handles DMA2 stream7 global interrupt.
*/
void DMA2_Stream7_IRQHandler(void)
{
/* USER CODE BEGIN DMA2_Stream7_IRQn 0 */
/* USER CODE END DMA2_Stream7_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_usart1_tx);
/* USER CODE BEGIN DMA2_Stream7_IRQn 1 */
/* USER CODE END DMA2_Stream7_IRQn 1 */
}
/**
* @brief Handles DMA interrupt request.
* @param hdma pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA Stream.
* @retval None
*/
void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
{
uint32_t tmpisr;
__IO uint32_t count = 0;
uint32_t timeout = SystemCoreClock / 9600;
/* calculate DMA base and stream number */
DMA_Base_Registers *regs = (DMA_Base_Registers *)hdma->StreamBaseAddress;
tmpisr = regs->ISR;
/* Transfer Error Interrupt management ***************************************/
if ((tmpisr & (DMA_FLAG_TEIF0_4 << hdma->StreamIndex)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET)
{
/* Disable the transfer error interrupt */
hdma->Instance->CR &= ~(DMA_IT_TE);
/* Clear the transfer error flag */
regs->IFCR = DMA_FLAG_TEIF0_4 << hdma->StreamIndex;
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_TE;
}
}
/* FIFO Error Interrupt management ******************************************/
if ((tmpisr & (DMA_FLAG_FEIF0_4 << hdma->StreamIndex)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_FE) != RESET)
{
/* Clear the FIFO error flag */
regs->IFCR = DMA_FLAG_FEIF0_4 << hdma->StreamIndex;
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_FE;
}
}
/* Direct Mode Error Interrupt management ***********************************/
if ((tmpisr & (DMA_FLAG_DMEIF0_4 << hdma->StreamIndex)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_DME) != RESET)
{
/* Clear the direct mode error flag */
regs->IFCR = DMA_FLAG_DMEIF0_4 << hdma->StreamIndex;
/* Update error code */
hdma->ErrorCode |= HAL_DMA_ERROR_DME;
}
}
/* Half Transfer Complete Interrupt management ******************************/
if ((tmpisr & (DMA_FLAG_HTIF0_4 << hdma->StreamIndex)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET)
{
/* Clear the half transfer complete flag */
regs->IFCR = DMA_FLAG_HTIF0_4 << hdma->StreamIndex;
/* Multi_Buffering mode enabled */
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != RESET)
{
/* Current memory buffer used is Memory 0 */
if((hdma->Instance->CR & DMA_SxCR_CT) == RESET)
{
if(hdma->XferHalfCpltCallback != NULL)
{
/* Half transfer callback */
hdma->XferHalfCpltCallback(hdma);
}
}
/* Current memory buffer used is Memory 1 */
else
{
if(hdma->XferM1HalfCpltCallback != NULL)
{
/* Half transfer callback */
hdma->XferM1HalfCpltCallback(hdma);
}
}
}
else
{
/* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */
if((hdma->Instance->CR & DMA_SxCR_CIRC) == RESET)
{
/* Disable the half transfer interrupt */
hdma->Instance->CR &= ~(DMA_IT_HT);
}
if(hdma->XferHalfCpltCallback != NULL)
{
/* Half transfer callback */
hdma->XferHalfCpltCallback(hdma);
}
}
}
}
/* Transfer Complete Interrupt management ***********************************/
if ((tmpisr & (DMA_FLAG_TCIF0_4 << hdma->StreamIndex)) != RESET)
{
if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET)
{
/* Clear the transfer complete flag */
regs->IFCR = DMA_FLAG_TCIF0_4 << hdma->StreamIndex;
if(HAL_DMA_STATE_ABORT == hdma->State)
{
/* Disable all the transfer interrupts */
hdma->Instance->CR &= ~(DMA_IT_TC | DMA_IT_TE | DMA_IT_DME);
hdma->Instance->FCR &= ~(DMA_IT_FE);
if((hdma->XferHalfCpltCallback != NULL) || (hdma->XferM1HalfCpltCallback != NULL))
{
hdma->Instance->CR &= ~(DMA_IT_HT);
}
/* Clear all interrupt flags at correct offset within the register */
regs->IFCR = 0x3FU << hdma->StreamIndex;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY;
if(hdma->XferAbortCallback != NULL)
{
hdma->XferAbortCallback(hdma);
}
return;
}
if(((hdma->Instance->CR) & (uint32_t)(DMA_SxCR_DBM)) != RESET)
{
/* Current memory buffer used is Memory 0 */
if((hdma->Instance->CR & DMA_SxCR_CT) == RESET)
{
if(hdma->XferM1CpltCallback != NULL)
{
/* Transfer complete Callback for memory1 */
hdma->XferM1CpltCallback(hdma);
}
}
/* Current memory buffer used is Memory 1 */
else
{
if(hdma->XferCpltCallback != NULL)
{
/* Transfer complete Callback for memory0 */
hdma->XferCpltCallback(hdma);
}
}
}
/* Disable the transfer complete interrupt if the DMA mode is not CIRCULAR */
else
{
if((hdma->Instance->CR & DMA_SxCR_CIRC) == RESET)
{
/* Disable the transfer complete interrupt */
hdma->Instance->CR &= ~(DMA_IT_TC);
/* Process Unlocked */
__HAL_UNLOCK(hdma);
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY;
}
if(hdma->XferCpltCallback != NULL)
{
/* Transfer complete callback */
hdma->XferCpltCallback(hdma);
}
}
}
}
/* manage error case */
if(hdma->ErrorCode != HAL_DMA_ERROR_NONE)
{
if((hdma->ErrorCode & HAL_DMA_ERROR_TE) != RESET)
{
hdma->State = HAL_DMA_STATE_ABORT;
/* Disable the stream */
__HAL_DMA_DISABLE(hdma);
do
{
if (++count > timeout)
{
break;
}
}
while((hdma->Instance->CR & DMA_SxCR_EN) != RESET);
/* Process Unlocked */
__HAL_UNLOCK(hdma);
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY;
}
if(hdma->XferErrorCallback != NULL)
{
/* Transfer error callback */
hdma->XferErrorCallback(hdma);
}
}
}

 该函数中主要关注半传输完成中断以及传输完成中断。

 对于半传输完成中断相关函数,其主要功能有:

  • 清除半传输完成中断标志位;
  • DMA_SxCR寄存器DBM位为复位状态,双缓冲器模式未使能;
  • DMA_SxCR寄存器CIRC位为复位状态,循环模式为禁止状态;禁用DMA半传输中断;
  • 本例中半传输完成中断回调函数为空函数,不执行任何操作。

 对于传输完成中断相关函数,其主要功能有:

  • 清除传输完成中断标志位;
  • 如果DMA状态为ABORT,禁用所有DMA中断,清除所有中断标志位,并调用ABORT回调函数;
  • DMA_SxCR寄存器DBM位为复位状态,双缓冲器模式未使能;
  • DMA_SxCR寄存器CIRC位为复位状态,循环模式为禁止状态;
  • 调用传输完成中断回调函数UART_DMATransmitCplt(),该函数具体如下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @brief DMA UART transmit process complete callback
* @param hdma DMA handle
* @retval None
*/
static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode*/
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0U)
{
huart->TxXferCount = 0U;
/* Disable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAT);
/* Enable the UART Transmit Complete Interrupt */
SET_BIT(huart->Instance->CR1, USART_CR1_TCIE);
}
/* DMA Circular mode */
else
{
HAL_UART_TxCpltCallback(huart);
}
}

UART_DMATransmitCplt()的功能如下:

  • 本例中DMA模式为Normal;
  • DMA发送计数器置零;
  • 禁止DMA发送模式;
  • 通过置位USARTx_CR1寄存器TCIE位,软件产生一个UART传输完成中断。

UART中断服务函数

 UART中断服务函数如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/**
* @brief This function handles USART1 global interrupt.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
/* USER CODE END USART1_IRQn 1 */
}
/**
* @brief This function handles UART interrupt request.
* @param huart uart handle
* @retval None
*/
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
uint32_t isrflags = READ_REG(huart->Instance->ISR);
uint32_t cr1its = READ_REG(huart->Instance->CR1);
uint32_t cr3its = READ_REG(huart->Instance->CR3);
uint32_t errorflags;
/* If no error occurs */
errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE));
if (errorflags == RESET)
{
/* UART in mode Receiver ---------------------------------------------------*/
if(((isrflags & USART_ISR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
UART_Receive_IT(huart);
return;
}
}
/* If some errors occur */
if( (errorflags != RESET)
&& ( ((cr3its & USART_CR3_EIE) != RESET)
|| ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET)) )
{
/* UART parity error interrupt occurred -------------------------------------*/
if(((isrflags & USART_ISR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET))
{
__HAL_UART_CLEAR_IT(huart, UART_CLEAR_PEF);
huart->ErrorCode |= HAL_UART_ERROR_PE;
}
/* UART frame error interrupt occurred --------------------------------------*/
if(((isrflags & USART_ISR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
__HAL_UART_CLEAR_IT(huart, UART_CLEAR_FEF);
huart->ErrorCode |= HAL_UART_ERROR_FE;
}
/* UART noise error interrupt occurred --------------------------------------*/
if(((isrflags & USART_ISR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
__HAL_UART_CLEAR_IT(huart, UART_CLEAR_NEF);
huart->ErrorCode |= HAL_UART_ERROR_NE;
}
/* UART Over-Run interrupt occurred -----------------------------------------*/
if(((isrflags & USART_ISR_ORE) != RESET) &&
(((cr1its & USART_CR1_RXNEIE) != RESET) || ((cr3its & USART_CR3_EIE) != RESET)))
{
__HAL_UART_CLEAR_IT(huart, UART_CLEAR_OREF);
huart->ErrorCode |= HAL_UART_ERROR_ORE;
}
/* Call UART Error Call back function if need be --------------------------*/
if(huart->ErrorCode != HAL_UART_ERROR_NONE)
{
/* UART in mode Receiver ---------------------------------------------------*/
if(((isrflags & USART_ISR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
UART_Receive_IT(huart);
}
/* If Overrun error occurs, or if any error occurs in DMA mode reception,
consider error as blocking */
if (((huart->ErrorCode & HAL_UART_ERROR_ORE) != RESET) ||
(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)))
{
/* Blocking error : transfer is aborted
Set the UART state ready to be able to start again the process,
Disable Rx Interrupts, and disable Rx DMA request, if ongoing */
UART_EndRxTransfer(huart);
/* Disable the UART DMA Rx request if enabled */
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
/* Abort the UART DMA Rx channel */
if(huart->hdmarx != NULL)
{
/* Set the UART DMA Abort callback :
will lead to call HAL_UART_ErrorCallback() at end of DMA abort procedure */
huart->hdmarx->XferAbortCallback = UART_DMAAbortOnError;
/* Abort DMA RX */
if(HAL_DMA_Abort_IT(huart->hdmarx) != HAL_OK)
{
/* Call Directly huart->hdmarx->XferAbortCallback function in case of error */
huart->hdmarx->XferAbortCallback(huart->hdmarx);
}
}
else
{
/* Call user error callback */
HAL_UART_ErrorCallback(huart);
}
}
else
{
/* Call user error callback */
HAL_UART_ErrorCallback(huart);
}
}
else
{
/* Non Blocking error : transfer could go on.
Error is notified to user through user error callback */
HAL_UART_ErrorCallback(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
}
}
return;
} /* End if some error occurs */
/* UART in mode Transmitter ------------------------------------------------*/
if(((isrflags & USART_ISR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET))
{
UART_Transmit_IT(huart);
return;
}
/* UART in mode Transmitter (transmission end) -----------------------------*/
if(((isrflags & USART_ISR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET))
{
UART_EndTransmit_IT(huart);
return;
}
}
/**
* @brief Wrap up transmission in non-blocking mode.
* @param huart pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart)
{
/* Disable the UART Transmit Complete Interrupt */
CLEAR_BIT(huart->Instance->CR1, USART_CR1_TCIE);
/* Tx process is ended, restore huart->gState to Ready */
huart->gState = HAL_UART_STATE_READY;
HAL_UART_TxCpltCallback(huart);
return HAL_OK;
}
/**
* @brief Tx Transfer completed callbacks
* @param huart uart handle
* @retval None
*/
extern uint8_t uartReady;
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
uartReady = 1;
}

 这里主要关注中断传输完成中断:

  • TC软件置位产生的中断传输完成中断中调用UART_EndTransmit_IT()函数;
  • UART_EndTransmit_IT()函数复位USARTx_CR1寄存器TCIE位,禁止传输完成中断;继而调用HAL_UART_TxCpltCallback()函数;
  • HAL_UART_TxCpltCallback()函数为自定义函数。

实验验证

 验证程序设置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
uint8 sendStr[65535] = "1234567890";
uint8 uartReady = 1;
while (1)
{
mainloop++;
oled_putuint32(0, 2, mainloop);
oled_putuint32(0, 3, __HAL_DMA_GET_COUNTER(&hdma_usart1_tx));
if (uartReady == TRUE)
{
uartReady = FALSE;
test = HAL_UART_Transmit_DMA(&huart1,sendStr,sizeof(sendStr));
}
}

 其基本原理为调用HAL_UART_Transmit_DMA()函数进行发送,同时通过__HAL_DMA_GET_COUNTER()获取DMA数据流传输中的剩余数据数目并实时显示。当DMA发送完成并通过TC为触发UART中断后,将uartReady置位,此时可以进行新一轮DMA传输。

 实验结果为:OLED显示器实时显示DMA数据流传输的剩余数据数目;串口接收软件可以接收到发送的数据(但是由于数据流速率过高,串口软件有时无法正常显示)。

文章目录
  1. 1. 开发环境
    1. 1.1. 硬件环境
    2. 1.2. 软件环境
  2. 2. DMA的基本特性
    1. 2.1. 系统框图
    2. 2.2. 主要特性
    3. 2.3. DMA通道选择
  3. 3. DMA的基本设置
    1. 3.1. DMA通道选择
    2. 3.2. DMA时钟与NVIC初始化
    3. 3.3. UART初始化
    4. 3.4. HAL_DMA_Init()实现
    5. 3.5. __HAL_LINKDMA()实现
  4. 4. 基于DMA的UART发送实现
    1. 4.1. HAL_UART_Transmit_DMA()实现
    2. 4.2. HAL_DMA_Start_IT()实现
    3. 4.3. DMA中断服务函数
    4. 4.4. UART中断服务函数
  5. 5. 实验验证
|