简体   繁体   中英

UART loopback test using HAL for STM32L0

I am new to MCU programming. I'd like to test UART loopback (mirror) using HAL. IAR project was generated by CubeMX for STM32L071RZT6. This code is in the main eternal loop:

HAL_UART_Transmit(&huart2, str1, 5, 1000); HAL_UART_Receive(&huart2, str2, 5, 1000);

I get only the 1st element filled in str2 (null-terminated string). How can I fix it?

/* USART2 init function */
 static 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;
   huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
   huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
   if (HAL_UART_Init(&huart2) != HAL_OK)
   {
    _Error_Handler(__FILE__, __LINE__);
   }

}

You can't send & receive at the same time. HAL_UART_Transmit is a blocking function, so when the function returns the data has been sent. When you call HAL_UART_Receive the data has been received. You should do something like that:

HAL_UART_Receive_IT(&huart2, str2, 5);
HAL_UART_Transmit(&huart2, str1, 5, 1000);

You can do it by interrupt or by DMA, but you should start receive before send.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM