简体   繁体   中英

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 ie 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.

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
        //...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM