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

一、关于DataReceive事件。
主程序必须有

outserialPort.DataReceived +=new SerialDataReceivedEventHandler(outserialPort_DataReceived);//注册received事件

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

二、读取串口数据的两种方法
第一种是采用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();

注意:
1、ReadLine()方法一直会读到有一个新的行才会返回,所以如果发送数据中没有换行符则该方法不会返回,会一直停留在readline程序里不会执行之后的程序,而read()是调用者自己定义一个byte数组来接收串口中缓存里的数据,byte多长就读多长
参考:http://bbs.csdn.net/topics/330233058

2、 string receivedata=System.Text.Encoding.ASCII.GetString(buf);
注意串口接收的编码是ASCII型而不是Unicode否则无法读出接收的数据

三、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这个名称可以自取。


四、如何知道当前电脑有哪个串口


方法1:

comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());  

方法2:

string[] portList = System.IO.Ports.SerialPort.GetPortNames();

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

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

 

五、参考资料:
1、C#串口操作系列教程:http://blog.csdn.net/wuyazhe/article/category/695097
2、C# SerialPort运行方式:(关于如何读取接收数据)http://www.cnblogs.com/lzjsky/archive/2011/04/07/2008089.html

 

 

原文地址:https://www.cnblogs.com/shenbing/p/6323152.html