没有在C#中读取完整的串口数据

mgr*_*oss 5 c# serial-port

我正在使用.Net framework 4并在C#中创建一个串口GUI应用程序.在某些情况下,SerialPort对象(端口)不会接收所有数据(我将其与混合信号示波器进行比较)

例如,如果连接的设备发送:

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

我可以收到:

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

我尝试了具有相同问题的不同代码:

  • 使用数据接收事件填充缓冲区:

        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;
            }
        }
    
    Run Code Online (Sandbox Code Playgroud)
  • 循环使用预期的字节数,在这种情况下导致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...
    
    Run Code Online (Sandbox Code Playgroud)

我试图改变ReadBufferSize大小,超时信息......但没有任何作用.有任何想法吗?

Joe*_*Joe 2

尝试在串行端口上配置软件(XON/XOF)或硬件(例如RTS/CTS)握手,以匹配正在传输的设备的配置。