使用了SerialPort类接收串口通讯的报文。报文格式是0xF3 xx xx xx。。。xx xx 0xFD。其中报头是F3,报尾是FD。xx是数据,报文长度是不固定的。相邻两个报文之间间隔约500毫秒。考虑了下面几种判断报文的方法,但是都不成功:
1、采用最常见的方法,设置属性port.ReceivedBytesThreshold ,收到设定数量的字节数据后触发接收事件port.DataReceived,因为报文长度不固定,所以无法使用这个方法。
2、使用读取方法port.ReadTo(Encoding.ASCII.GetString(new byte[1] { 0xFD })),当读到报尾时则停止。调试发现,始终读不到数据,估计原因是ascii值0xFD对应的不是一个可打印字符。
3、感觉最合理的方法应该是:当串口持续一段时间例如100ms,没有收到数据,则读取缓冲区所有数据,并判断报头报尾。但是这种方法怎样写代码呢?SerialPort.ReadTimeout似乎并不合适。难道是要开一个100mS的timer吗?
4、因为一个报文里的相邻两个字节数据之间,时间间隔几乎等于零,所以每接收到一个字节就去读取并判断一次,这样的方法时间上来不及。
应该采用哪种方法呢?望高手指教,感谢!
...全文
716820打赏收藏
串口应该采用什么方法接收报文?
使用了SerialPort类接收串口通讯的报文。报文格式是0xF3 xx xx xx。。。xx xx 0xFD。其中报头是F3,报尾是FD。xx是数据,报文长度是不固定的。相邻两个报文之间间隔约500毫秒。考虑了下面几种判断报文的方法,但是都不成功: 1、采用最常见的方法,设置属性port.ReceivedBytesThreshold ,收到设定数量的字节数据后触发接收事件port.DataReceived,因为报文长度不固定,所以无法使用这个方法。 2、使用读取方法port.ReadTo(En
不想说啥,如果你只愿意看博客园的,只愿意采用博客园的我们说啥都没有用
我们只能说在博客园之外,全世界的其他程序员采用的通用方式是
Transfer 层-------------------------基于 System.IO.Pipelines的 IDuplexPipe方式
//IDuplexPipe is defined in System.IO.Pipelines, but they provide no default implementation!!! So something like the below occurs all over the place: SignalR, etc. Also, Input and Output are awful names, but I agree they're hard to name.
// BACK //
// output input //
// --------------- //
// writer reader //
// || /\ //
// || || //
// || || //
// || || //
// \/ || //
// reader writer //
// --------------- //
// input output //
// FRONT //
我们只能说在博客园之外,全世界的其他程序员采用的通用方式是
Transfer 层-------------------------基于 System.IO.Pipelines的 IDuplexPipe方式
//IDuplexPipe is defined in System.IO.Pipelines, but they provide no default implementation!!! So something like the below occurs all over the place: SignalR, etc. Also, Input and Output are awful names, but I agree they're hard to name.
不想说啥,如果你只愿意看博客园的,只愿意采用博客园的我们说啥都没有用
我们只能说在博客园之外,全世界的其他程序员采用的通用方式是
Transfer 层-------------------------基于 System.IO.Pipelines的 IDuplexPipe方式
//IDuplexPipe is defined in System.IO.Pipelines, but they provide no default implementation!!! So something like the below occurs all over the place: SignalR, etc. Also, Input and Output are awful names, but I agree they're hard to name.
// BACK //
// output input //
// --------------- //
// writer reader //
// || /\ //
// || || //
// || || //
// || || //
// \/ || //
// reader writer //
// --------------- //
// input output //
// FRONT //