none
SerialPort receives data as 2 part RRS feed

  • Question

  • Hello everyone,

    Icould get data from SerialPort but receives as 2 part. Normally data must be 01  02  00  0B  00  01  C8  08 but writes 01 to buffer first and then receives 02  00  0B  00  01  C8  08. My codes are below:

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
           byte[] buff = new byte[port.BytesToRead];
           Console.WriteLine(port.BytesToRead);
           port.Read(buff, 0, buff.Length);
           SetText(buff);
    }

    Output is:

    Thank you for your helps

    Friday, December 8, 2017 7:47 AM

Answers

  • This falls into the category of:  That is expected.

    Serial data is a stream and there is no guarantees how the "chunks" will be delivered to your program.  Any time you work with serial data, you should expect to move the data to some sort of buffer and then parse the buffer into meaningful messages/packets.  It is common for a single message to be chopped up into multiple "chunks" that your application receives, but you should also be prepared to receive multiple messages in a single "chunk" as well.

    If serial programming is new to you, you may be tempted to play with the threshold properties to try and get your "chunks" to match up with messages from your remote device.  I will just suggest from experience:  That is a bad idea.  Things may seem to work at your desk, but somewhere, somehow the data will still sometimes come in chunks that you don't expect.  Easier to just do the parsing up front.


    Friday, December 8, 2017 5:07 PM