#STM32F串口通过DMA收发
在使用STM32CUBEMAX,进行DMA收发原本很简单,被网上的一些文章,给误导了两天,今天我把自已的心得发在这文章内,供大家参考
自先在STM32CUBEMAX进行设置,为表达方便,我直接用图片了
main.c
#include "main.h"
#include "dma.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
//#include "string.h"
volatile char rx_data[32];//==定义一个接收缓存==
volatile uint16_t len; //接收了多少数据
volatile uint8_t rx_flag=0;//接收标志
/* USER CODE END Includes */
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
//接收标志有信号了,将接收到的串口数据,再通过DMA回显出来
if(rx_flag)
{
rx_flag=0;
HAL_UART_Transmit_DMA(&huart2,(uint8_t *)((uint32_t)&rx_data),len);
len=0;
}
HAL_Delay(500);
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
通过串口进行DMA 发送,是最容易的事只需要一句语句即可
HAL_UART_Transmit_DMA(&huart2,(uint8_t *)((uint32_t)&rx_data),len);
如果只要接收一次,你直接可以用一句也行
HAL_UART_Receive_DMA(&huart2,(uint8_t *)((uint32_t)&rx_data),32);
它接收的是固定长度
如要接收不固定长度需要串口中断配合,当串口发生了空闲中断,说明一帧已经接收完毕
在初始化串口时,要加入如下代码
下面展示一些 内联代码片
。
void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
HAL_UART_DMAStop(&huart2);
__HAL_UART_ENABLE_IT(&huart2,UART_IT_IDLE);
HAL_UART_Receive_DMA(&huart2,(uint8_t *)((uint32_t)&rx_data),32);
/* USER CODE END USART2_Init 2 */
}
在中断中添加如下代码
下面展示一些 内联代码片
。
void USART2_IRQHandler(void)
{
/* USER CODE BEGIN USART2_IRQn 0 */
uint32_t idle_flag_temp=0;
uint16_t len_temp=0;
/* USER CODE END USART2_IRQn 0 */
HAL_UART_IRQHandler(&huart2);
/* USER CODE BEGIN USART2_IRQn 1 */
idle_flag_temp=__HAL_UART_GET_FLAG(&huart2,UART_FLAG_IDLE);
if(idle_flag_temp)
{
__HAL_UART_CLEAR_FLAG(&huart2,UART_FLAG_IDLE);
HAL_UART_DMAStop(&huart2);
len_temp=__HAL_DMA_GET_COUNTER(&hdma_usart2_rx);
len=32-len_temp;
rx_flag=1;
}
HAL_UART_Receive_DMA(&huart2,(uint8_t *)((uint32_t)&rx_data),32);