简体   繁体   中英

Timeouts in C# serial port

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM