gpt4 book ai didi

c# - 不在 C# 中读取完整的串口数据

转载 作者:太空狗 更新时间:2023-10-29 23:10:59 26 4
gpt4 key购买 nike

我正在使用 .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;
    }
    }
  • 循环预期的字节数,在这种情况下会导致 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...

我尝试更改 ReadBufferSize 大小、超时信息……但没有任何效果。有什么想法吗?

最佳答案

这段代码中有细微的错误。第一个片段的 Array.Resize() 什么都不做,也许 buffer 需要改为调整大小?当接收到的字节数 多于 expectedSize 时,第二个代码片段在 TimeoutException 上爆炸。这当然是可能的,而不是超时问题。

但我认为真正的问题在于您在这段代码之外对数组执行的操作。通常,调用 SerialPort.Read() 只会让您获得几个字节。串行端口很慢。您需要某种协议(protocol)来了解何时收到“完整”响应。一个非常常见的(非二进制)是简单地用换行符终止响应。然后您只需在 DataReceived 事件处理程序中使用 ReadLine()。在您的情况下,正确的方法是什么并不明显。

同时实现 ErrorReceived 事件。它会在发生错误时告诉您,例如 SerialError.Overrun 或 RXOver,这些错误也会使字节消失。

关于c# - 不在 C# 中读取完整的串口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com