在.NET串口通讯 [英] Serial port communication in .NET

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

问题描述

我使用C#从串行口接收数据,但也存在一些问题。我是新来这个,所以我需要一些帮助。




  1. 首先关闭所有我想知道哪些功能是事件驱动的:



 
ReadExisting()
阅读()
Readbyte()
Readchar( )
的ReadLine()
Readto()




  1. 如何利用这个端口所需的数据表单输入流?



    我有静态尺寸的协议。我可以使用特殊字符来指定一个协议数据的极限,这将是这一个合适的字符


  2. 我要如何处理这个异常:<? / p>


    C#的SerialPort System.ObjectDisposedException,安全拉手已经在System.dll中关闭




解决方案

这些方法都不是事件驱动,你会在DataReceived事件检索使用它们。其中,当串行端口具有数据的至少一个字节可供读取被称为



不确定什么静态尺寸的意思。如果设备发送的字节固定数量的,那么你会使用Read()方法来阅读。要注意的返回值,你会因为可只得到尽可能多的字节。在一个byte []数据储存并追加到,在未来的DR事件,直到你有他们所有。



如果设备发送的字符,而不是字节,那么你就可以通常采取换行符财产优势。其设置为终止响应的字符或字符串。一个换行符(\\\
)是迄今为止最典型的选择。阅读的ReadLine响应()。无缓冲要求在这种情况下。



当你关闭一个形式,但不保证该设备停止发送数据,您会得到ObjectDisposed例外。请务必仅使用的BeginInvoke在DataReceived事件检索,不能调用。不要调用BeginInvoke如果窗体的IsDisposed属性为true。


I am using C# to receive data from a serial port but there are some problems. I'm new to this so I need some help.

  1. First off all I want to know which functions are event driven:

ReadExisting()
Read()
Readbyte() 
Readchar()
ReadLine()
Readto()

  1. How can I take the required data form input stream of this port?

    I have static sized protocols. Can I use a special char to specify limits of a protocol data, and which will be a suitable char for this?

  2. How do I handle this exception:

    C# SerialPort System.ObjectDisposedException, safe handle has been closed in System.DLL

解决方案

None of these methods are "event driven", you'd use them in the DataReceived event. Which is called when the serial port has at least one byte of data available to read.

Not sure what "static sized" means. If the device sends a fixed number of bytes then you'd use the Read() method to read them. Pay attention to the return value, you'll get only as many bytes as are available. Store them in a byte[] and append to that in the next DR event until you've got them all.

If the device sends characters rather than bytes then you can usually take advantage of the NewLine property. Set it to the character or string that terminates the response. A linefeed ("\n") is by far the most typical choice. Read the response with ReadLine(). No buffering is required in that case.

You'll get the ObjectDisposed exception when you close a form but don't ensure that the device stops sending data. Be sure to use only BeginInvoke in the DataReceived event, not Invoke. And don't call BeginInvoke if the form's IsDisposed property is true.

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

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