【问题标题】:High USB-Rate causes error in consuming data高 USB 速率导致消费数据错误
【发布时间】:2023-02-03 05:52:18
【问题描述】:

我有一个使用 .net 核心和带有 raspberry pi OS 的 raspberry pi(计算模块 4)构建的应用程序。 我有两个线程,每个线程负责每 0.5 毫秒从不同的 USB 端口接收(200 字节)的数据。 当只有一个线程在工作时,一切正常,但是当两个线程一起工作时,这会在读取串行缓冲区时出现异常,这会导致数据丢失。

Linux USB 缓冲区有任何限制吗? 还是应该考虑这种做法的另一个问题? 或者内存有问题?

接收代码:

try
{
int availableBytes = serialPort.BytesToRead;

if (availableBytes > 0)
{
byte[] receivedBytes = new byte[availableBytes];

serialPort.Read(receivedBytes, 0, receivedBytes.Length);

return receivedBytes;
}
}
catch (Exception ex)
{

}

例外:

  • 错误异常消息:操作已超时。
  • 异常 StackTrace:在 System.IO.Ports.SerialStream.Read(字节 [] 数组、Int32 偏移量、Int32 计数、Int32 超时) 在 System.IO.Ports.SerialPort.Read(字节 [] 缓冲区,Int32 偏移量,Int32 计数) 在 F:\MainBoardSW\HAL\Serial\UsbDriver.cs 中的 MainBoardSW.HAL.Serial.UsbDriver.ReadAvailableData():第 126 行

谢谢你 。

【问题讨论】:

    标签: c# .net-core raspberry-pi usbserial


    【解决方案1】:

    请记住SerialPort.Read() 方法不能保证读取 SerialPort.BytesToRead 属性报告的所有可用字节. SerialPort.Read() 方法返回一个整数,表示实际读取的字节数。有关详细信息,请参阅SerialPort.Read() reference page 的“备注”部分。有很多方法可以处理这种异常,下面显示了其中一种。

        try
        {
            byte[] receivedBytes;
            byte[] tempBuffer;
            int actualBytes = 0;
            int expectedBytes = serialPort.BytesToRead;
            if (expectedBytes > 0)
            {
                tempBuffer = new byte[expectedBytes];
                actualBytes = serialPort.Read(tempBuffer, 0, tempBuffer.Length);
                receivedBytes = new byte[actualBytes];
                System.Array.Copy(tempBuffer, receivedBytes , actualBytes); 
                return receivedBytes;
            }
        }
        catch (Exception ex)
        {
        
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 2014-03-02
      • 1970-01-01
      相关资源
      最近更新 更多