Timeouts in C# serial port

人走茶凉 提交于 2019-12-13 04:28:40

问题


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#.


回答1:


running at baud rates 460800 to 921600

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.

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:

  • Implement the ErrorReceived event so you know that overflows occur
  • Favor using the DataReceived event so you don't depend on calling Read() frequently enough
  • Set the ReadBufferSize to a nice big number so the driver can take up the slack
  • Set the Handshake property so the driver can tell the device to stop sending when the buffer is full
  • Check if you can implement a protocol so the device doesn't just fire-hose the machine
  • Lower the baud rate if it still isn't reliable enough.


来源:https://stackoverflow.com/questions/14863881/timeouts-in-c-sharp-serial-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!