在c#上读取Com端口
请告诉我如何在c#中从com端口读取数据,如果数据以字节为单位接收,但是长度可变,也就是说,答案可能是字节数组20和50,这就是主要问题是,如何做您知道设备停止响应吗?
Please tell me how to read data from com port in c #, if the data is received in bytes, but of variable length, that is, the answer may be a byte array 20 and 50, that is the main question is, how do you know that the device stopped responding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最重要的部分是定义所使用的协议位。您应该有起始位和停止位来告诉您的 SerialPort 对象何时停止读取。通常您不必关心这一点,因为您的回调函数将包含数组中的数据。
http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx
The most important part is defining the protocol bits used. You should have both start and stop bits that will tell your SerialPort object when to stop reading. Usually you don't have to care after this since your callback function will contain the data in an array.
http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx
你不知道。 COM 端口有点像 TCP - 它们是流媒体服务 - 它们一次仅传输 7 或 8 位(取决于您如何设置端口,通常为 8 位)。
如果你想发送比字节更复杂的东西,你需要在上面构建一个协议。如果您的数据是文本,则末尾的 CR 或 null 通常就可以了。如果它的值在整个字节集 0-255 中,那么您需要更复杂的协议来确保正确接收数据单元的帧。也许您的要求可以通过简单的超时来满足,例如“如果 500 毫秒内没有收到任何字符,则数据单元结束”,但这样的超时协议显然性能较低并且容易失败:(
Rgds,
马丁
You don't. COM ports are a bit like TCP - they're a streaming service - they only transfer 7 or 8 bits at a time, (depending on how you set the port up, normally 8 bits).
If you want to send anything more complex than a byte, you need to build a protocol on top. If your data is text, a CR or null at the end will often do. If it's values in the whole set of bytes 0-255, then you need a more complex protocol to ensure that the framing of the data-units is received correctly. Maybee your requirements can be met by a simple timeout, eg 'if no chars received for 500ms, that's the end of the data unit', but such timeout-protocols are obviously low performance and subject to failures:(
Rgds,
Martin