Arduino Serial Communication not receiving entire message

ⅰ亾dé卋堺 提交于 2019-12-13 15:19:14

问题


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

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

when it should be:

hello done

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.


回答1:


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.

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:

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


来源:https://stackoverflow.com/questions/12754972/arduino-serial-communication-not-receiving-entire-message

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