在STM32F4中通过UART接收字符串 [英] Receiving a string through UART in STM32F4

查看:126
本文介绍了在STM32F4中通过UART接收字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码来通过 USART6 接收一系列字符变量并将它们存储在一个字符串中.但问题是第一次收到的价值只是个垃圾!任何帮助将不胜感激.

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);
    }

函数原型

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

推荐答案

首先,HAL_Delay 似乎是多余的.有什么特别的原因吗?HAL_UART_Receive_IT 函数用于非阻塞模式.你写的似乎更像是阻塞模式,它使用了 HAL_UART_Receive 函数.

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:

主要部分:

// 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);

然后是回调函数:

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);   
}

这个想法是始终只接收一个字节并将其保存到一个数组中.然后在某处检查接收到的字节数或一些模式检查等,然后处理接收到的帧.另一方面,如果字节数始终相同,则可以更改HAL_UART_Receive_IT";函数并设置正确的字节数.

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.

这篇关于在STM32F4中通过UART接收字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆