小编mgr*_*oss的帖子

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

我正在使用.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(); …
    Run Code Online (Sandbox Code Playgroud)

c# serial-port

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

serial-port ×1