本文将介绍如何在.NET平台下使用C#创建串口通信程序,.NET2.0提供了串口通信的功能,其命名空间是System.IO.Ports。这个新的框架不但可以访问计算机上的串口,还可以和串口设备进行通信。我们将使用标准的RS232C在PC间通信。它工作在全双工模式下,而且我们不打算使用任何的握手或流控制器,而是使用无modem连接。命名空间System.IO.Ports命名空间中最重用的是SerialPort类。创建SerialPort对象通过创建SerialPort对象,我们可以在程序中控制串口通信的全过程。我们将要用到的SerialPort类的方法:ReadLine():从输入缓冲区读一新行的值,如果没有,会返回NULLWriteLine(string):写入输出缓冲Open():打开一个新的串口连接Close():关闭Code://createaSerialPortobjectSerialPortsp=newSerialPort();默认情况下,DataBits值是8,StopBits是1,通信端口是COM1。这些都可以在下面的属性中重新设置:BaudRate:串口的波特率StopBits:每个字节的停止位数量ReadTimeout:当读操作没有完成时的停止时间。单位,毫秒还有不少其它公共属性,自己查阅MSDN。串口的硬件知识在数据传输的时候,每个字节的数据通过单个的电缆线传输。包包括开始位,数据,结束为。一旦开始位传出,后面就会传数据,可能是5,6,7或8位,就看你的设定了。发送和接收必须设定同样的波特率和数据位数。无猫模式没有Modem模式的电缆只是简单地交叉传送和接收线。同样DTR&DSR,和RTS&CTS也需要交叉。RS232针图这里,我们三条线。互连2和3(一段的2pin连接3pin),连接两端的5pin。[示例程序]主程序如果想使用默认属性,按“SaveStatus”按钮,如果想改变属性按“Property”。它会弹出下图:设定好之后,可以通信了。主窗口的代码Code:#regionUsingdirectivesusingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Windows.Forms;usingSystem.IO.Ports;#endregionnamespaceSerialexpample{partialclassForm1:Form{//createinstanceofpropertypage//propertypageisusedtosetvaluesforstopbitsand//baudratePropertyPagepp=newPropertyPage();//createanSerialPortobjectSerialPortsp=newSerialPort();publicForm1(){InitializeComponent();}privatevoidpropertyButton_Click(objectsender,EventArgse){//showpropertydialogpp.ShowDialog();propertyButton.Hide();}privatevoidsendButton_Click(objectsender,EventArgse){try{//writelinetoserialportsp.WriteLine(textBox.Text);//clearthetextboxtextBox.Text=;}catch(System.Exceptionex){baudRatelLabel.Text=ex.Message;}}privatevoidReadButton_Click(objectsender,EventArgse){try{//clearthetextboxtextBox.Text=;//readserialportanddisplayedthedataintextboxtextBox.Text=sp.ReadLine();}catch(System.Exceptionex){baudRatelLabel.Text=ex.Message;}}privatevoidForm1_Load(objectsender,EventArgse){}privatevoidForm1_FormClosing(objectsender,FormClosingEventArgse){MessageBox.Show(DouwanttoClosetheApp);sp.Close();}privatevoidstartCommButton_Click(objectsender,EventArgse){startCommButton.Hide();sendButton.Show();readButton.Show();textBox.Show();}//whenwewanttosavethestatus(value)privatevoidsaveStatusButton_Click_1(objectsender,EventArgse){//displayvalues//ifnopropertyissetthedefaultvaluesif(pp.bRate==&&pp.sBits==){dataBitLabel.Text=BaudRate=+sp.BaudRate.ToString();readTimeOutLabel.Text=StopBits=+sp.StopBits.ToString();}else{dataBitLabel.Text=BaudRate=+pp.bRate;readTimeOutLabel.Text=StopBits=+pp.sBits;}parityLabel.Text=DataBits=+sp.DataBits.ToString();stopBitLabel.Text=Parity=+sp.Parity.ToString();readTimeOutLabel.Text=ReadTimeout=+sp.ReadTimeout.ToString();if(propertyButton.Visible==true)propertyButton.Hide();saveStatusButton.Hide();startCommButton.Show();try{//openserialportsp.Open();//setreadtimeoutto500mssp.ReadTimeout=500;}catch(System.Exceptionex){baudRatelLabel.Text=ex.Message;}}}}属性设置对话框代码:Code:#regionUsingdirectivesusingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;#endregionnamespaceSerialexpample{partialclassPropertyPage:Form{//variablesforstoringvaluesofbaudrateandstopbitsprivatestringbaudR=;privatestringstopB=;//propertyforsettingandgettingbaudrateandstopbitspublicstringbRate{get{returnbaudR;}set{baudR=value;}}publicstringsBits{get{returnstopB;}set{stopB=value;}}publicPropertyPage(){InitializeComponent();}privatevoidcancelButton_Click(objectsender,EventArgse){this.bRate=;this.sBits=;//closeformthis.Close();}privatevoidokButton_Click_1(objectsender,EventArgse){//herewesetthevalueforstopbitsandbaudrate.this.bRate=BaudRateComboBox.Text;this.sBits=stopBitComboBox.Text;//this.Close();}}}一.概述在VisualStudio6.0中编写串口通讯程序,一般都使用MicrosoftCommunicationControl(简称MSComm)的通讯控件,只要通过对此控件的属性和事件进行相应编程操作,就可以轻松地实现串口通讯。但在Microsoft.Net技术广泛应用的今天,VisualStudio.Net没有将此控件加入控件库,所以人们采用了许多方法在VisualStudio.Net来编写串口通讯程序:第一种方法是通过采用VisualStudio6.0中原来的MSComm控件这是最简单的,最方便的方法,但需要注册;第二种方法是采用微软在.NET推出了一个串口控件,基于.NET的P/Invoke调用方法实现;第三种方法是自己用API写串口通信,虽然难度高,但可以方便实现自己想要的各种功能。现在微软推出了最新版本的VisualStudio2005开发工具,可以不再采用第三方控件的方法来设计串口通讯程序。NETFramework2.0类库包含了SerialPort类,方便地实现了所需要串口通讯的多种功能,为了使MSComm编程方法快速转换到以SerialPort类为核心的串口通讯的设计方法,本文着重讨论了VisualStudio6.0的MSComm控件和SerialPort类设计方法的异同点。二.SerialPort常用属性、方法和事件1.命名空间System.IO.Ports命名空间包含了控制串口重要的SerialPort类,该类提供了同步I/O和事件驱动的I/O、对管脚和中断状态的访问以及对串行驱动程序属性的访问,所以在程序代码起始位置需加入UsingSystem.IO.Ports。2.串口的通讯参数串口通讯最常用的参数就是通讯端口号及通讯格式(波特率、数据位、停止位和校验位),在MSComm中相关的属性是CommPort和Settings。SerialPort类与MSComm有一些区别:a.通讯端口号[PortName]属性获取或设置通信端口,包括但不限于所有可用的COM端口,请注意该属性返回类型为String,不是Mscomm.CommPort的short类型。通常情况下,PortName正常返回的值为COM1、COM2……,SerialPort类最大支持的端口数突破了CommPort控件中CommPort属性不能超过16的限止,大大方便了用户串口设备的配置。b.通讯格式SerialPort类对分别用[BaudRate]、[Parity]、[DataBits]、[StopBits]属性设置通讯格式中的波特率、数据位、停止位和校验位,其中[Parity]和[StopBits]分别是枚举类型Parity、StopBits,Parity类型中枚举了Odd(奇)、Even(偶)、Mark、None、Space,Parity枚举了None、One、OnePointFive、Two。SerialPort类提供了七个重载的构造函数,既可以对已经实例化的SerialPort对象设置上述相关属性的值,也可以使用指定的端口名称、波特率和奇偶校验位数据
本文标题:C中串口通信编程
链接地址:https://www.777doc.com/doc-2908373 .html