STM32—cubeIDE+DMA+USART receives data of any length

You can find a lot of relevant information on the Internet about usart serial port sending and receiving information, but most of them can only send limited characters. Some can send unlimited characters, but most of them cannot be used directly, which is not very friendly to novices. Just do the following, it’s actually very simple to achieve

1. Configure USART1, select asynchronous, and the software automatically configures the PA9 and PA10 pins.

2. Configure the clock tree, I use the default one, and then generate the code.

3. Modify the UASRT serial port program

Let me first declare:

volatile uint8_t rx_len = 0;             //接收一帧数据的长度
volatile uint8_t recv_end_flag = 0;    //一帧数据接收完成标志
uint8_t rx_buffer[200]={0};   //接收数据缓存

Modify static void MX_USART1_UART_Init(void) function

Just copy it directly, the code is as follows:  

__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);          //使能IDLE中断
  HAL_UART_Receive_DMA(&huart1,rx_buffer,BUFFER_SIZE);

3. Modify the serial port interrupt function (stm32f4xx_it.c).

void USART1_IRQHandler(void) //Serial port interrupt
{     uint32_t tmp_flag = 0;     uint32_t temp;

    HAL_UART_IRQHandler(&huart1);
    if(USART1 == huart1.Instance)
    {         tmp_flag =__HAL_UART_GET_FLAG(&huart1,UART_FLAG_IDLE); //Prepare IDLE setting

        if((tmp_flag != RESET))//idle flag is set
        {             recv_end_flag = 1; //Accept completion flag position 1             __HAL_UART_CLEAR_IDLEFLAG(&huart1);//Clear flag bit

            HAL_UART_DMAStop(&huart1); //
            temp = __HAL_DMA_GET_COUNTER(&hdma_usart1_rx); // Get the number of untransmitted data in DMA
            rx_len = BUFFER_SIZE - temp; // Subtract the total count from the number of untransmitted data to get the number of received data number

            HAL_UART_Receive_DMA(&huart1,rx_buffer,BUFFER_SIZE);//Re-open DMA reception
        }
    }
 }

4. For the serial port interrupt processing function in the main function, add the following code to the main() function:

 while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
      if(recv_end_flag ==1)
              {                   printf("rx_len=%d\r\n",rx_len);//Print the received length                   HAL_UART_Transmit(&huart1,rx_buffer, rx_len,200);// Print out the received data                   for(uint8_t i=0;i<rx_len;i++)                       {                           rx_buffer[i]=0;//Clear the receive buffer                       }                   rx_len=0;//Clear the count                   recv_end_flag=0;//Clear the receive end flag bit               }               HAL_UART_Receive_DMA(&huart1,rx_buffer,BUFFER_SIZE);//Re-open DMA reception









  }
  /* USER CODE END 3 */

5. Hurry up and compile and test. You can return as many characters as you want.

Guess you like

Origin blog.csdn.net/llq_the7/article/details/108649569