1
votes

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.

1
Welcome to StackExchange! That's pretty good for a first question -- if you mention the actual namespace and class names that you're using, your question will be both easier to answer (so more likely to attract an answer) and also easier to find in the future. Even better if you link to the reference manual, and quote the part you're having trouble with.RJHunter
there might be a couple of reasons (maybe it was fired before your read the bytes) - can you show your code? Maybe we can help you cope with the issue (as it really should be no issue) insteadRandom Dev
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.Alex Howard
please edit your question and put the code there - it's absolutely unreadable in the comment - also have you checked the answer Hans gave you bellow?Random Dev
on top of it - DisplayText seems not to display text - it seems to read data from the port so it seems to be really misnamed plus you should do this in the event itself ;)Random Dev

1 Answers

7
votes

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