Not reading Serial Port data in C #

I am using .Net framework 4 and am creating a serial port GUI application in C #. In some cases, the SerialPort object (port) does not receive all the data (I compare it with a mixed signal oscilloscope)

For example, if a connected device sends:

0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09

I can get:

0x00 0x01 0x02 0x03 0x04 0x08 0x09

I tried different codes with the same problem:

  • Use the data to fill the buffer:

        private void dataReceived(object sender, SerialDataReceivedEventArgs e) {
            while (port.BytesToRead > 0){
                byte[] newBytes = new byte[port.BytesToRead];
                int LengthRead = port.Read(newBytes, 0, newBytes.Length);
                Array.Resize(ref newBytes, LengthRead);
                System.Buffer.BlockCopy(newBytes, 0, buffer, positionInBuffer, newBytes.Length);
                positionInBuffer += newBytes.Length;
            }
        }
    
  • Looping for the expected number of bytes, in this case throwing a TimeoutException:

            while (port.BytesToRead < expectedSize)
        {
            System.Threading.Thread.Sleep(10);
            waitingLoop++;
            if (waitingLoop > TimeOut)             // wait for a 1s timeout
                throw new TimeoutException();
        }
    
        newBytes = new byte[expectedSize];
        LengthRead = port.Read(newBytes, 0, newBytes.Length);
        if (LengthRead != newBytes.Length)
            throw new TimeoutException(); // or any exception, doesn't matter...
    

I tried resizing ReadBufferSize, timeout information, but nothing works. Any ideas?

+5
3

. Array.Resize() , , ? TimeoutException, , . , , , -.

, , . SerialPort.Read() . . - , , "" . ( ) - . ReadLine() DataReceived. , .

ErrorReceived. , - , SerialError.Overrun RXOver, , .

+3

(XON/XOF) (, RTS/CTS) .

+2

.

- . - :

<ID><SIZE><DATA....><CHECKSUM>

, SIZE, ( 1000 115200, ). , , ( ), #, ( ). 2- , TimeOutException ( ), , 1 ( 5 ). , , SerialPort.Read().

, ErrorReceived, , -...

Regarding Array.Resize (), I wrote this if the SerialPort.Read () returned data has fewer bytes than expected. The buffer is predefined at the maximum size of my SerialPort buffer (4096). As for my second error in the code, you are quite right. I should use a more appropriate exception :)

0
source

All Articles