user2083401
user2083401

Reputation: 11

Working with SerialPort´s DataReceived Event

Im trying to read the output of a device on a COM port on my PC. Im wrote a C# program to do so. Using PuTTY, I can see the output Im expecting from my device. The problem is that the function SerialPort.ReadExisting(); in my DataReceived function gives my a completely different string. What is the proper way to read from a COM port using SerialPort?

Also, the strings I get from SerialPort.ReadExisting(); are fragments of the string I sent to the device.

Below is the code that initializes the SerialPort.

    SerialPort port;

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string data = port.ReadExisting();
    }

    void init_serialport(object sender, EventArgs e)
    {
        if (port != null)
        {
            port.Close();
        }

        port = new SerialPort( /* ... */ );
        port.BaudRate = 9600;
        port.Parity = Parity.None;
        port.DataBits = 8;
        port.StopBits = StopBits.One;
        port.Handshake = Handshake.RequestToSend;

        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

        try
        {
            port.Open();
        }
        catch (Exception ex)
        {
             // ...
        }
    }

Upvotes: 1

Views: 4103

Answers (3)

Jeff
Jeff

Reputation: 1362

You received fragments because SerialPort.Existing() executes and completes in less time then it takes for your sending device to send the entire string.

You need to repeat the call continuously or until you received the end of string character if the string has one.

Upvotes: 0

Marcello Romani
Marcello Romani

Reputation: 3144

the strings I get from SerialPort.ReadExisting(); are fragments of the string I sent to the device.

I'd have a look at SerialPort.ReceivedBytesThreshold.

"Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs."

Upvotes: 1

David W
David W

Reputation: 10184

I would first take a look at the Read method of the port object, look at the raw bytes and verify that they match your expectations, which would then narrow down the problem to the encoding on the conversion to string.

More information on this is provided here.

Upvotes: 0

Related Questions