Arduino 串行通信未收到完整消息 [英] Arduino Serial Communication not receiving entire message

查看:44
本文介绍了Arduino 串行通信未收到完整消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Arduino 通信有问题.这很难描述,所以我无法将其放入标题中.无论如何,这里有以下内容:

I have a problem with the Arduino communication. It's quite hard to describe so I cant fit it in the title. Anyway here are the following:

所以我的接收端有这个代码:

So I have this code for my receiving end:

if(Serial1.available())
{
    while(Serial1.available())
    {
        uint8_t inByte = Serial1.read();

        inByte = inByte ^ k;

        Serial.write(inByte); 
    }

    Serial.println(" done");
}

它应该在一行中打印并在完成时打印完成.Serial1.available()好像跳过了下一个Serial1.available(),不知道怎么回事.无论如何,这是我当前的糟糕输出:

It's supposed to print in one line and print done when it's done. The Serial1.available() seems to skip the next Serial1.available(), I don't know what's going on. Anyway here's my current, bad, output:

h done
e done
l done
l done
o done

done

应该什么时候:

hello done

对不起,如果这可以用更好的措辞表达,但我现在只能打字,我的大脑有点痛.我从未在 Windows C++ 控制台应用程序中遇到过这种行为.

I'm sorry if this could've been phrased better but that's all I can type now, my brain is kinda in pain. I've never experienced this behavior in a Windows c++ console application.

推荐答案

如果您在 loop() 中调用该例程,则是的,它将从串行缓冲区读取并立即返回,因为您发送数据的速度可能不够快.

If you are calling that routine in loop() then yes, it will read from the serial buffer and immediately return since you are probably not sending the data fast enough.

处理此类事情的更好方法是使用指示消息结束的控制字符,或者如果您有希望接收的特定数据格式,则保持对已进入的字符的计数,直到已达到数据格式限制.

A better way to handle this sort of thing is to use a control char which indicates the end of a message OR if you have a specific data format you expect to receive, then keep a count of the chars which have come in until the data format limit is reached.

这里有一些你可能会觉得有用的讨论:Serial Duplex using Arduino 还有Arduino IDE 附带的示例草图:菜单:示例:通信:

There is discussion here which you may find useful: Serial Duplex using Arduino Also there are example sketches that ship with the Arduino IDE: Menu: Examples: Communication:

此外,阅读 Arduino 的 Serial 列表下的所有条目.好东西.

Also, read all the entries under the Serial listing for Arduino. Good stuff there.

因此,您为处理串行输入而开发的例程实际上取决于您的项目和您接收的数据类型.在上面的示例中,如果您要使用控制字符,它可能如下所示:

So the routine you develop for working with Serial input really depends on your project and the kind of data you are receiving. In your example above, if you were to use a control char, it might look like this:

 while(Serial1.available()){
   char c = Serial1.read();

   if (c == '*'){
       Serial.println(" done");
   } else {
       Serial.write(c); 
   } 
 }

这篇关于Arduino 串行通信未收到完整消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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