2、类。创建C#串口通信程序之创建SerialPort对象通过创建SerialPort对象,我们可以在程序中控制串口通信的全过程。我们将要用到的SerialPort类的方法:ReadLine():从输入缓冲区读一新行的值,如果没有,会返回NULLWriteLine(string):写入输出缓冲Open():打开一个新的串口连接Close():关闭1.//create a Serial Port object 2.SerialPort sp = new SerialPort (); 默认情况下,DataBits值是8,StopBits是1,通信端口是COM1。这些都可以在下面的属性中重新设置:
5、s; 10. 11.#endregion 12. 13.namespace Serialexpample 14.{ 15.partial class Form1 : Form 16.{ 17.//create instance of property page 18.//property page is used to set values for stop bits and 19.//baud rate 20. 21.PropertyPage pp = new PropertyPage(); 22. 23.//create an Serial Port object 1.SerialP
7、17.{ 18.try 19.{ 20.//write line to serial port 21.sp.WriteLine(textBox.Text); 22.//clear the text box 23.textBox.Text = ""; 24.} 25.catch (System.Exception ex) 26.{ 27.baudRatelLabel.Text = ex.Message; 28.} 29. 30.} 3