stm32l552ret 串口接收DMA空闲中断
接收数组定义:
#pragma pack(4)
unsigned char UART_DMA_BUFF[255];
#pragma pack()
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600;
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.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_7_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_EnableFifoMode(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
//使能串口空闲中断
__HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE);
//DMA 接收地址设置
HAL_UART_Receive_DMA(&huart1,UART_DMA_BUFF,255);
/* USER CODE END USART1_Init 2 */
}
加入的是这两行
串口接收里改成这样
#include "string.h"
extern unsigned char UART_DMA_BUFF[255];
unsigned char data_length;
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
if(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE) != RESET)
{
/* USER CODE BEGIN USART1_IRQn 1 */
__HAL_UART_CLEAR_IDLEFLAG(&huart1);//清楚串口二空闲中断的标志位
HAL_UART_DMAStop(&huart1);
data_length = 255 - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx); //计算接收到的数据长度
HAL_UART_Transmit(&huart1,UART_DMA_BUFF,data_length,0x200); //测试函数:将接收到的数据打印出去
memset(UART_DMA_BUFF, 0 ,255); //清除数组
HAL_UART_Receive_DMA(&huart1, UART_DMA_BUFF, 255);
}
/* USER CODE END USART1_IRQn 1 */
}
验证如下:
附完整工程:
链接:https://pan.baidu.com/s/1EfFHEPwW1IwcBzTusqNm2A
提取码:1573