Serial read/write fragmented issue
Issue #430
resolved
I did a serial port test and found that when writing a string to the serial port, like "abc", it may be split into two separate transmissions. This means that when reading from the serial port, sometimes I receive "a" first and then "bc".
How can I ensure that the strings I send and receive are complete and not fragmented?
Comments (3)
-
repo owner -
repo owner - changed status to open
-
repo owner - changed status to resolved
I hope my explanation helped. I'm going to close this issue but feel free to ask additional questions.
- Log in to comment
This isn't a bug, it's the nature of serial communications.
There are various ways you can arrange to get "complete" messages.
One way is to have the receiver do multiple serial read operations, appending any bytes read to byte array stored in a variable. If the message is a fixed size, the receive process is done when the byte array once it reaches that size. Or, the receive process might collect incoming bytes for a fixed amount of time, then return whatever it has received.
The above tricks work if the sender only sends data when asked to do so. That is, the receiver sends a request, then waits for a response. The sender sends a response, then waits for the next request. Many microcontroller peripherals (e.g. MP3 players) work this way.
If the sender can send data at any time, you need a way to chop the incoming bytes into discrete messages (or "packets"). Such schemes typically have a way to indicate the start of a message (e.g. a special "start" byte value). Messages often have a size field to indicate the number of bytes in that message and they sometimes have a checksum or CRC code to check for transmission errors. See the "packet structure" section of this [XMODEM Wikipedia article] (https://en.wikipedia.org/wiki/XMODEM) for a simple example.