C#串口超时 [英] Timeouts in C# serial port

查看:207
本文介绍了C#串口超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 C# 串行端口库与传感器和 PC 通信.即使那里有数据,我也经常使用 SerialPort.Read() 方法超时.我使用串行嗅探器来检查我是否在端口接收了所有数据包,但有些 .NET 没有选择所有数据包并超时.我正在读取字节,我收到的字节比串行端口缓冲区大小小 2112.我尝试了多种方法,现在考虑使用原生 C/C++ 并在 C# 中调用它.有人可以分享更多想法或在 C# 中使用原生 C/C++ 代码.

I am using the C# Serial port library for communicating with a sensor and PC . I am frequently getting timeouts with the SerialPort.Read() method even though there is data in there. I used serial sniffers to check that I am receiving all the packet at the port but some how .NET does not pick all of them and times out. I am reading bytes and the bytes I am receiving is 2112 less than the serial port buffer size. I tried multiple things and now thinking of using native C/C++ and calling it in C#. Can someone share more thoughts or used native C/C++ code in C#.

推荐答案

以 460800 到 921600 的波特率运行

running at baud rates 460800 to 921600

那些非常奇怪的波特率,相当高.很明显,您没有使用 DataReceived 事件,因此调用 Read() 方法的频率变得相当重要.花一些时间做其他事情,包括 Windows 认为需要做一些更重要的事情并且上下文切换远离您的线程,并且接收缓冲区将迅速溢出.未实现 SerialPort.ErrorReceived 事件是一个标准错误,因此您看不到这些溢出,您看到的只是丢失数据.

Those are pretty strange baud rates, rather high. Clearly you are not using the DataReceived event so it gets rather critical how often you call the Read() method. Take some time off doing something else, including Windows thinking that something more important needs to be done and context-switches away from your thread, and the receive buffer will quickly overflow. Not implementing the SerialPort.ErrorReceived event is a standard mistake so you just don't see those overflows, all you see is missing data.

用 C++ 编写这段代码不太可能带来缓解.串行端口只有一个 api,SerialPort 只是一个薄包装器,并且像 C++ 代码一样使用 winapi 函数.

Writing this code in C++ is very unlikely to bring relieve. There's only one api for serial ports, SerialPort is just a thin wrapper and uses the winapi functions like your C++ code would.

因此,请执行以下所有步骤:

So take all of the following steps:

  • 实现 ErrorReceived 事件,以便您知道发生溢出
  • 倾向于使用 DataReceived 事件,这样您就不必过于频繁地调用 Read()
  • 将 ReadBufferSize 设置为一个不错的大数字,以便驱动程序可以弥补这一点
  • 设置 Handshake 属性,以便驱动程序可以告诉设备在缓冲区已满时停止发送
  • 检查您是否可以实施协议,以便设备不只是对机器进行消防水管
  • 如果仍然不够可靠,请降低波特率.

这篇关于C#串口超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆