Receiving a string through UART in STM32F4

萝らか妹 提交于 2021-01-28 12:33:54

问题


I've written this code to receive a series of char variable through USART6 and have them stored in a string. But the problem is first received value is just a junk! Any help would be appreciated in advance.

while(1)
{
            
    //memset(RxBuffer, 0, sizeof(RxBuffer));            
    i = 0;
    requestRead(&dt, 1);   
    RxBuffer[i++] = dt;
            
    while (i < 11)
    {
         requestRead(&dt, 1);
         RxBuffer[i++] = dt;
         HAL_Delay(5);
    }

function prototype

static void requestRead(char *buffer, uint16_t length)
{
    while (HAL_UART_Receive_IT(&huart6, buffer, length) != HAL_OK)
    HAL_Delay(10);     
}

回答1:


First of all, the HAL_Delay seems to be redundant. Is there any particular reason for it? The HAL_UART_Receive_IT function is used for non-blocking mode. What you have written seems to be more like blocking mode, which uses the HAL_UART_Receive function.

Also, I belive you need something like this:

Somewhere in the main:

// global variables
volatile uint8_t Rx_byte;
volatile uint8_t Rx_data[10];
volatile uint8_t Rx_indx = 0;

HAL_UART_Receive_IT(&huart1, &Rx_byte, 1);

And then the callback function:

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)  
{
   if (huart->Instance == UART1) { // Current UART
      Rx_data[Rx_indx++] = Rx_byte;    // Add data to Rx_Buffer
      }

   HAL_UART_Receive_IT(&huart1, &Rx_byte, 1);   
}

The idea is to receive always only one byte and save it into an array. Then somewhere check the number of received bytes or some pattern check, etc and then process the received frame. On the other side, if the number of bytes is always same, you can change the "HAL_UART_Receive_IT" function and set the correct bytes count.



来源:https://stackoverflow.com/questions/63087338/receiving-a-string-through-uart-in-stm32f4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!