【问题标题】:Incomplete data reading from serial port c#从串口c#读取数据不完整
【发布时间】:2014-07-30 03:26:49
【问题描述】:

我在读取从串口传输的数据时遇到问题(每次第一次运行项目时数据不完整)。

我尝试了两种阅读方法:

byte[] data = new byte[_serialPort.BytesToRead];
_serialPort.Read(data, 0, data.Length);
txtGateway.Text = System.Text.Encoding.UTF8.GetString(data);

txtGateway.Text = _serialPort.ReadExisting();

但是,当我启动程序时,它每次第一次只读取 14 个字节。当我跟踪程序时,_serialPort.BytesToRead 每次第一次只给出 14 个。如果我第二次发送数据,则数据被正确读取。

以上两种方法的结果是一样的。我确信从串口写入数据会给出完整的数据。

【问题讨论】:

  • BytesToReadReadExisting 都不可靠。

标签: c# serial-port


【解决方案1】:

串行端口没有任何消息边界。如果你想取景,你必须自己添加。

当您的程序启动时,串行端口中只有最近的 14 个字节,14 个字节是串行端口的典型 FIFO 大小。 另见How do you programmatically configure the Serial FIFO Receive and Transmit Buffers in Windows?

或者只是在程序启动时刷新接收缓冲区。

【讨论】:

    【解决方案2】:

    您好,您可以将数组与回车符 \r 和 ascii 代码 \x02 用于 STX

    string data = _serialPort.ReadExisting();
    string[] arr1 = data.Split('\r');
    checkFinal = checkFinal.Replace("\x02", "").ToString().Trim();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-07
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多