1
votes

How we know with SerialPort class in c# when we receive all the data from the device connected on the serial port ?

There is my code. How i know i received all the data from the device ?

private void button1_Click(object sender, RoutedEventArgs e)
        {
    p = new SerialPort("COM5");
                if (!p.IsOpen)
                {
                    try
                    {
                        p.Open();
                        p.DataReceived += new SerialDataReceivedEventHandler(p_DataReceived);
                        p.PinChanged += new SerialPinChangedEventHandler(p_PinChanged);                       
                      Data = "Port ouvert";
                    }
                    catch (Exception ex)
                    {
                        Data = string.Format("Erreur ouverture du port : {0}", ex.Message);
                    }
                }}


    void p_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {

                var serial = (SerialPort)sender;

                string line = serial.ReadExisting();

                string data =  string.Format("Donné recu : {0}",line);          
                Data = data;
                strb.Append(line);

            }
3
It's application dependent. If you are expecting 20 bytes and you get 20 bytes, then you've got all the data.Steve Wellens

3 Answers

5
votes

how do you imagine to have received all data? The device can always send you some more later.

For example we had a medical device which used to send lines of text to a serially connected printer (one of those old pins printers able to print one line at time and keep on the same page), we replaced the printer with a computer and made a software able to append in a TextArea the lines of text as they came from the Serial port.

in this way, you should listen to the serial port and detect a new line terminated with the proper line break code and handle that new line but you do have to stay connected and see if other data is coming afterwards.

I would say it depends on your device if you know that once it completes a certain operation will send you a special code then check for that code, otherwise just stay connected and listen to all incoming data.

2
votes

You can check the SerialDataReceivedEventArgs.EventType property. If it's SerialData.Eof, that most likely means that all data has been received.

1
votes

The Serial port has a way of sending data. It puts it into a buffer and will continue to read as fast as the buffer can be emptied and the protocol can send data.

What you are asking is above the level of the serial port. You need to know the interface for the type of device you are communicating with. You must know what to expect from the device which will dictate when you are finished listening. You will also need to write error handling code for the situations where you aren't sent all the data you require.