Alex Howard
Alex Howard

Reputation: 11

Serial Port object's DataReceived Event firing twice

I am using visual C# 2010 windows forms application serial port object to receive hex data bytes on serial port.
However, I realized that my DataReceived event is fired twice even though I have read all the data bytes in the buffer and buffer shows 0 bytes to read.
Why and how does that happen?

private void PortData(Object Sender,     System.IO.Ports.SerialDataReceivedEventArgs e)
{
    this.Invoke(new EventHandler(delegate { DisplayText(); }));
}

Private void DisplayText()
{
    int dataLength = serialPort1.BytesToRead;
    byte[] data = new byte[dataLength];
    serialPort1.Read(data, 0, dataLentgh)
}

I am sending 8 hex bytes on serial port i-e FF FF FB FB FB FF FB which are received in data array by Read Function. But after this PortData function is invoked second time to read 0 bytes. I dont want it to invoke second time.

Upvotes: 1

Views: 2684

Answers (1)

Hans Passant
Hans Passant

Reputation: 941218

That is entirely normal when you receive binary data. Forgetting to check the e.EventType property is a standard bug. The event is raised whenever you receive a byte value of 0x1A, the end-of-file character. Not being able to set the EOF character, or disable it completely, is an oversight. You can only ignore them:

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
        if (e.EventType == System.IO.Ports.SerialData.Eof) return;
        // Rest of code
        //...
    }

Upvotes: 7

Related Questions