Search code examples
c#.netserial-portserial-communication

.NET serial-ports - receiving missing data


I'm working on a serialport application. And i'm not able to receive data properly. I'm using ReadExisting() for reading coming data. serialport- receiving missing data

and here is my code. Please advice, what is the proper way to receive data and what if i want to check the length of each message and the validity of format.

public void serialport_connect(String port, int baudrate, Parity parity, int databits, StopBits stopbits)
        {
            DateTime dt = DateTime.Now;
            String dtn = dt.ToShortTimeString();

            sport = new System.IO.Ports.SerialPort(port, baudrate, parity, databits, stopbits);

            try
            {
                sport.Open();
                status.AppendText("[" + dtn + "] " + "Connected\n");
                sport.DataReceived += new SerialDataReceivedEventHandler(sport_DataReceived);
            }
            catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); }
        }

        private void sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            DateTime dt = DateTime.Now;
            String dtn = dt.ToShortTimeString();
            String comingData = sport.ReadExisting();

            if (comingData != String.Empty)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    current.AppendText("[" + dtn + "] " + "Received: " + sport.ReadExisting() + "\n");
                }));
            }

        }

Thank You.


Solution

  • Your event loop is much faster then the time required to send a single character at 9600 baud. I would recommend appending the received characters to a string until you receive a terminating char like "\n" or your receive the number of characters you expect.

    Here is an example from a project where I wait until I receive 10 characters:

    int datalen = serialPort1.BytesToRead;
    label1.Text="Readexisting";
    if (datalen >=10)
    {
        string data = serialPort1.ReadExisting();
        label1.Text=data;
    }