STM32F103 serial port DMA + idle interrupt for variable length data transmission and reception

    There are two articles in the serial port DMA series, one is to use DMA + idle interrupt to send and receive data of variable length, the other is to use DMA interrupt to send and receive fixed-length data, the article link is as follows:
    01 STM32F103 Serial DMA + idle interrupt to realize variable length Data transceiver
    02 STM32F103 serial port + DMA interrupt to achieve data transceiver

    DMA (Direct Memory Access) is an important feature of all modern computers. It allows hardware devices of different speeds to communicate without relying on the massive interrupt load of the CPU. Otherwise, the CPU needs to copy the data of each segment from the source to the scratchpad, and then write them back to the new place again. During this time, the CPU cannot be used for other tasks.
    For the basic knowledge of DMA, please refer to the article https://blog.csdn.net/gdjason/article/details/51019219 . I personally feel that the last code part of the blogger’s article is a bit messy, so I will organize the records again. Serial DMA can have two interrupt triggering methods. One is to use STM32's IDLE idle interrupt to facilitate receiving data of variable length. This method is often used in use. The second is to use DMA's own transfer completion interrupt. The method can generate the transmission completion interrupt after the transmission is completed. The difference is that the idle interrupt is convenient for receiving data of variable length, and the DMA transmission completion interrupt will only generate the reception interrupt after receiving the defined length of data.
 

1. Idle interrupt

    This text uses the 485 bus to experiment the DMA idle interrupt of the serial port, and realize the data sending and receiving test. The difference of 485 is that there is an additional enable pin, which is high-level to enable transmission and low-level to enable reception, so it is half-duplex communication, and the others are consistent with the serial port. This example uses STM32F103 serial port 1, TX pin is PA9; RX pin is PA10, and the enable pin of 485 is PD1. When you use the serial port function test on the board, you don't need to consider the enable pin of 485. The part about 485 in this article is marked with /**** RS485 ****/, the following is the code part.

1.1 uart_dma.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_usart.h"
#include "stm32f10x_dma.h"
#include "misc.h"

#include "systick.h"	// 利用嘀嗒计时器实现了ms级的死等延时,用于切换485收发功能使用,实际项目中不能用死等延时
#include "uart_dma.h"

uint8_t uart1RecvData[32] = {
    
    0};    // 接收数据缓冲区
uint8_t uart1RecvFlag = 0;          // 接收完成标志位
uint8_t uart1RecvLen = 0;           // 接收的数据长度

uint8_t uart1SendData[32] = {
    
    0};    // 发送数据缓冲区
uint8_t uart1SendFlag = 0;          // 发送完成标志位

/* 串口1 GPIO引脚初始化 */
void Uart1GpioInit(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStruct;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);   // 使能GPIOA时钟

	/************ ↓ RS485 相关 ↓ ************/
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);   // 使能GPIOD时钟
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;    // 输入输出使能引脚 推挽输出
    GPIO_InitStruct.GPIO_Pin = UART1_EN_PIN;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(UART1_EN_PORT, &GPIO_InitStruct);     // PD1
    Uart1RxEnable();    // 初始化接收模式
    /************ ↑ RS485 相关 ↑ ************/
    
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;    // TX 推挽输出
    GPIO_InitStruct.GPIO_Pin = UART1_TX_PIN;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(UART1_TX_PORT, &GPIO_InitStruct);     // PA9
    
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU;      // RX上拉输入
    GPIO_InitStruct.GPIO_Pin = UART1_RX_PIN;
    GPIO_Init(UART1_RX_PORT, &GPIO_InitStruct);     // PA10
}

/************ ↓ RS485 相关 ↓ ************/
/* 使能485发送 */
void Uart1TxEnable(void)
{
    
    
    GPIO_WriteBit(UART1_EN_PORT, UART1_EN_PIN, Bit_SET);    // 485的使能引脚,高电平为使能发送
    Delay_ms(5);
}

/* 使能485接收 */
void Uart1RxEnable(void)
{
    
    
    GPIO_WriteBit(UART1_EN_PORT, UART1_EN_PIN, Bit_RESET);  // 485的使能引脚,低电平为使能发送
    Delay_ms(5);
}
/************ ↑ RS485 相关 ↑ ************/
 
/* 串口1配置 9600 8n1 */
void Uart1Config(void)
{
    
    
    USART_InitTypeDef USART_InitStruct;		// 串口配置
    NVIC_InitTypeDef NVIC_InitStructure;	// 中断配置
    DMA_InitTypeDef DMA_InitStruct;			// DMA 配置
    
    USART_DeInit(USART1);   // 寄存器恢复默认值
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);  // 使能串口时钟
    
    /* 串口参数配置 */
    USART_InitStruct.USART_BaudRate = BAUD_RATE;            // 波特率:9600
    USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;    // 无流控
    USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;    // 收发
    USART_InitStruct.USART_Parity = USART_Parity_No;                // 无校验位 
    USART_InitStruct.USART_StopBits = USART_StopBits_1;             // 1个停止位
    USART_InitStruct.USART_WordLength = USART_WordLength_8b;        // 8个数据位
    USART_Init(USART1, &USART_InitStruct);
    USART_Cmd(USART1, ENABLE);  // 使能串口
    
    /* 串口中断配置 */
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;             // 使能
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;   // 抢占优先级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;          // 子优先级
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;           // 串口1中断
    NVIC_Init(&NVIC_InitStructure);     // 嵌套向量中断控制器初始化

    USART_ITConfig(USART1, USART_IT_TC,   ENABLE);  // 使能串口发送中断,发送完成产生 USART_IT_TC 中断
    USART_ITConfig(USART1, USART_IT_IDLE, ENABLE);  // 使能串口空闲中断,接收一帧数据产生 USART_IT_IDLE 空闲中断
    
    /* 串口DMA配置 */
    DMA_DeInit(DMA1_Channel4);  // DMA1 通道4,寄存器复位
    DMA_DeInit(DMA1_Channel5);  // DMA1 通道5,寄存器复位
    
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);  // 使能 DMA1 时钟
    
    // RX DMA1 通道5
    DMA_InitStruct.DMA_BufferSize = sizeof(uart1RecvData);      // 定义了接收的最大长度
    DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralSRC;             // 串口接收,方向是外设->内存
    DMA_InitStruct.DMA_M2M = DMA_M2M_Disable;                   // 本次是外设到内存,所以关闭内存到内存
    DMA_InitStruct.DMA_MemoryBaseAddr = (uint32_t)uart1RecvData;// 内存的基地址,要存储在哪里
    DMA_InitStruct.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;// 内存数据宽度,按照字节存储
    DMA_InitStruct.DMA_MemoryInc = DMA_MemoryInc_Enable;        // 内存递增,每次串口收到数据存在内存中,下次收到自动存储在内存的下一个位置
    DMA_InitStruct.DMA_Mode = DMA_Mode_Normal;                  // 正常模式
    DMA_InitStruct.DMA_PeripheralBaseAddr = USART1_BASE + 0x04; // 外设的基地址,串口的数据寄存器
    DMA_InitStruct.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;    // 外设的数据宽度,按照字节存储,与内存的数据宽度一致
    DMA_InitStruct.DMA_PeripheralInc = DMA_PeripheralInc_Disable;   // 接收只有一个数据寄存器 RDR,所以外设地址不递增
    DMA_InitStruct.DMA_Priority = DMA_Priority_High;            // 优先级
    DMA_Init(DMA1_Channel5, &DMA_InitStruct);
    
    // TX DMA1 通道4  
    DMA_InitStruct.DMA_BufferSize = 0;                          // 发送缓冲区的大小,初始化为0不发送
    DMA_InitStruct.DMA_DIR = DMA_DIR_PeripheralDST;             // 发送是方向是外设到内存,外设作为目的地
    DMA_InitStruct.DMA_MemoryBaseAddr =(uint32_t)uart1SendData; // 发送内存地址,从哪里发送
    DMA_Init(DMA1_Channel4, &DMA_InitStruct);
     
    USART_DMACmd(USART1, USART_DMAReq_Tx | USART_DMAReq_Rx, ENABLE);// 使能DMA串口发送和接受请求
    DMA_Cmd(DMA1_Channel5, ENABLE);     // 使能接收
    DMA_Cmd(DMA1_Channel4, DISABLE);    // 禁止发送
}

/* 清除DMA的传输数量寄存器 */
void uart1DmaClear(void)
{
    
    
    DMA_Cmd(DMA1_Channel5, DISABLE);    // 关闭 DMA1_Channel5 通道
    DMA_SetCurrDataCounter(DMA1_Channel5, sizeof(uart1RecvData));   // 重新写入要传输的数据数量
    DMA_Cmd(DMA1_Channel5, ENABLE);     // 使能 DMA1_Channel5 通道
}

/* 串口1发送数组 */
void uart1SendArray(uint8_t *arr, uint8_t len)
{
    
    
    if(len == 0)	// 判断长度是否有效
      return;
	
	uint8_t sendLen = len>sizeof(uart1SendData) ? sizeof(uart1SendData) : len;	// 防止越界

    /************ ↓ RS485 相关 ↓ ************/ 
    Uart1TxEnable();    // 使能发送
    /************ ↑ RS485 相关 ↑ ************/
    
    while (DMA_GetCurrDataCounter(DMA1_Channel4));  // 检查DMA发送通道内是否还有数据
    if(arr) 
      memcpy(uart1SendData, arr, sendLen);
    
    // DMA发送数据-要先关 设置发送长度 开启DMA
    DMA_Cmd(DMA1_Channel4, DISABLE);
    DMA_SetCurrDataCounter(DMA1_Channel4, sendLen);   // 重新写入要传输的数据数量
    DMA_Cmd(DMA1_Channel4, ENABLE);     // 启动DMA发送  
}

 

1.2 uart_dma.h

#ifndef _UART_DAM_H_
#define _UART_DMA_H_

#include <stdint.h>

#define UART1_TX_PORT   GPIOA
#define UART1_TX_PIN    GPIO_Pin_9
#define UART1_RX_PORT   GPIOA
#define UART1_RX_PIN    GPIO_Pin_10
#define UART1_EN_PORT   GPIOD
#define UART1_EN_PIN    GPIO_Pin_1
#define BAUD_RATE       (9600)

extern uint8_t uart1RecvData[32];
extern uint8_t uart1RecvFlag;
extern uint8_t uart1RecvLen;
extern uint8_t uart1SendFlag;

void Uart1GpioInit(void);
void Uart1Config(void);
void uart1DmaClear(void);
void uart1SendArray(uint8_t *arr, uint8_t len);

/************ ↓ RS485 相关 ↓ ************/ 
void Uart1RxEnable(void);
void Uart1TxEnable(void);
/************ ↑ RS485 相关 ↑ ************/

#endif  /* uart_dma.h */

 

1.3 main.c

#include "uart_dma.h"
#include "misc.h"

int main()
{
    
     
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);  // 设置中断优先级分组
    
    /************ ↓ RS485 相关 ↓ ************/ 
    SysTickInit();          // 嘀嗒计时器初始化,没用485可以省去
    /************ ↑ RS485 相关 ↑ ************/
    
    Uart1GpioInit();	// 串口GPIO初始化
    Uart1Config();		// 串口和DMA配置

    while(1)
    {
    
         
        if(uart1RecvFlag == 1)	// 接收到数据
        {
    
    
            uart1RecvFlag = 0;  // 接收标志清空
            uart1DmaClear();    // 清空DMA接收通道
            uart1SendArray(uart1RecvData, uart1RecvLen);        // 使用DMA发送数据
            memset(uart1RecvData, '\0', sizeof(uart1RecvData)); // 清空接收缓冲区
        }
        
        if(uart1SendFlag == 1)
        {
    
    
            uart1SendFlag = 0;  // 清空发送标志   
            Uart1RxEnable();    // 发送完成打开接收
        }
    }
}

 

1.4 stm32f10x_it.c

#include "stm32f10x_it.h"
#include "stm32f10x_usart.h"
#include "stm32f10x_dma.h"

#include "uart_dma.h"

void USART1_IRQHandler(void)    // 串口1 的中断处理函数
{
    
    
    uint8_t clear;

    if(USART_GetITStatus(USART1, USART_IT_IDLE) != RESET)   // 空闲中断
    {
    
    
        clear = USART1->SR; // 清除空闲中断
        clear = USART1->DR; // 清除空闲中断
        
        uart1RecvFlag = 1;  // 置接收标志位
        uart1RecvLen = sizeof(uart1RecvData) - DMA_GetCurrDataCounter(DMA1_Channel5);// 总的buf长度减去剩余buf长度,得到接收到数据的长度
    }   
    
    if(USART_GetITStatus(USART1, USART_IT_TC) != RESET)     // 发送完成
    {
    
    
        USART_ClearITPendingBit(USART1, USART_IT_TC);       // 清除完成标记
        DMA_Cmd(DMA1_Channel4, DISABLE);                    // 关闭DMA
        uart1SendFlag = 1;                                  // 设置发送完成标志位
    }
}

 

1.5 Effect demonstration

    This article uses the serial port to use the DMA idle interrupt to receive data of variable length. After receiving the data, the received data is sent out using DMA, and the serial port debugging assistant is used for debugging. The effect is as follows: You can see that when the data exceeds the defined maximum data (this For example, after 32 bytes), the receiver can only receive 32 data, and the other data will be discarded.
Insert picture description here
 

1.6 Knowledge supplement

1.6.1 Peripheral base address

    The peripheral to base address defined in this article is USART1_BASE + 0x04. Why is this? Check the STM32 reference manual, find the serial port chapter, and look up the USART register address map as shown below: You can see that the data register is the position after the serial port base address register offset 0x04. The macro definition of the serial port 1 base address can be found in stm32f10x.h, as shown in the figure below.
Insert picture description here
Serial port 1 base address macro definition
 

1.6.2 Idle interrupt clear

    After an idle interrupt is generated, read SR first, and then read DR to clear the idle interrupt flag bit, as shown in the figure below (Serial Port Chapter 25.6.1 Status Register (USART_SR) of the manual).
Insert picture description here
 

1.6.3 Number of DMA transfers

    Check the manual, the value in the DMA transfer quantity register indicates the number of bytes remaining to be transferred, so the total number defined in it.c-the value in the register = indicates the number received. This place needs special attention, otherwise the number of bytes received will be calculated incorrectly.
Insert picture description here
    Another point is that after each reception is completed, in order to make the next reception from the subscript 0 in the memory or store it, you need to rewrite the amount of data to be transmitted, otherwise the next time it will start receiving and storing directly from the position of the last transmission. The same is true when sending, see lines 127–129 and lines 149–151 in the code uart_dma.c.
    If line 128 is commented out, and the transfer quantity register is not rewritten each time, the demonstration result is as follows: From the result, it can be seen that if line 128 is commented out, the subscript will start from the last end position when DMA transfers data to the receiving buffer. The starting position [because the value of the transfer quantity register is not 0 at this time, it is 32-7], the front is'/0' because the receiving buffer is cleared after each reception. Therefore, after receiving a frame of data, the transfer quantity register must be cleared to 0.
Insert picture description here

    If you have any questions during the DMA learning process, welcome to communicate.

Guess you like

Origin blog.csdn.net/qq_36310253/article/details/109641759
Recommended