C#利用SerialPort控件进行串口编程小记(1)

1、关于DataReceive事件。
主程序必须有
outserialPort.DataReceived +=new SerialDataReceivedEventHandler(outserialPort_DataReceived);//注册received事件

建立 SerialDataReceivedEventHandler 委托即把接受数据的时间关联到相应的事件去。不然接收事件发生时没法触发对应的方法。
+=表示增长注册一种方法,而-=则相反。
html

2、读取串口数据的两种方法
第一种是采用read方法读取           
            int n = outserialPort.BytesToRead;
            byte[] buf = new byte[n];
            outserialPort.Read(buf, 0, n);
            string receivedata = System.Text.Encoding.ASCII.GetString(buf);
第二种是采用readline方法读取
            string receivedata = outserialPort.ReadLine();
注意:
一、ReadLine()方法一直会读到有一个新的行才会返回,因此若是发送数据中没有换行符则该方法不会返回,会一直停留在readline程序里不会执行以后的程序,而read()是调用者本身定义一个byte数组来接收串口中缓存里的数据,byte多长就读多长
参考:http://bbs.csdn.net/topics/330233058 数组

二、 string receivedata=System.Text.Encoding.ASCII.GetString(buf);
注意串口接收的编码是ASCII型而不是Unicode不然没法读出接收的数据 缓存

3、Invoke的两种书写方法: 函数

第一种
this.Invoke(new EventHandler(delegate
            {
                //要委托的代码
             }));
第二种
delegate void mydelegate(object sender, System.EventArgs e);  
mydelegate interfaceUpdateHandle;
而后再在主线程中
interfaceUpdateHandle = new mydelegate(button1_Click);  //实例化委托对象   
在附属线程中则
this.Invoke(interfaceUpdateHandle, null, null);
其中,invoke的参数数量应该要和声明的时候一致即和delegate后的函数参数数量一致。并且mydelegate这个名称能够自取。


4、如何知道当前电脑有哪一个串口 this


方法1:comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());   编码

方法2:string[] portList = System.IO.Ports.SerialPort.GetPortNames(); spa

            for (int i = 0; i < portList.Length; ++i)
            {
                string name = portList[i];
                comboBox1.Items.Add(name);
            }
.net

参考:http://blog.csdn.net/cy757/article/details/4474930 线程

5、参考资料: 一、C#串口操做系列教程:http://blog.csdn.net/wuyazhe/article/category/695097 二、C# SerialPort运行方式:(关于如何读取接收数据)http://www.cnblogs.com/lzjsky/archive/2011/04/07/2008089.html
相关文章
相关标签/搜索