STM32之串口DMA中断

定义变量

uint8_t aTxBuffer[100];    //存放要发送的字符串
uint8_t aRxBuffer[100];    //存放接收到的字符串
uint8_t usRxLen;           //实际接收到的数据长度
uint8_t Rx_flag;           //接收到数据时置1

在main函数中清idle标志位,并且开中断

HAL_UART_Receive_DMA(&huart2,aRxBuffer,sizeof(aRxBuffer));     //开启接收DMA
__HAL_UART_CLEAR_IDLEFLAG(&huart2);                            //清除IDLE中断标志
__HAL_UART_ENABLE_IT(&huart2,UART_IT_IDLE);                    //使能中断

在stm32loxx_it.c的中断函数中修改

void USART2_IRQHandler(void)
{
  /* USER CODE BEGIN USART2_IRQn 0 */
	uint8_t len;
  /* USER CODE END USART2_IRQn 0 */
  HAL_UART_IRQHandler(&huart2);
  /* USER CODE BEGIN USART2_IRQn 1 */
	if(__HAL_UART_GET_FLAG(&huart2,UART_FLAG_IDLE))
	{
		__HAL_UART_CLEAR_IDLEFLAG(&huart2);
		HAL_UART_DMAStop(&huart2);
		len = sizeof(aRxBuffer) - (__HAL_DMA_GET_COUNTER(&hdma_usart2_rx));
		if(len > 0)
		{
			memcpy(aTxBuffer,aRxBuffer,len);
			usRxLen = len;
			Rx_flag = 1;
		}
		HAL_UART_Receive_DMA(&huart2,aRxBuffer,sizeof(aRxBuffer));
	}
  /* USER CODE END USART2_IRQn 1 */
}

在wile(1)中

if(Rx_flag == 1)
{
	HAL_UART_Transmit_DMA(&huart2,aTxBuffer,usRxLen);
	Rx_flag = 0;
}

 

你可能感兴趣的:(STM32)