欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#串口通信程序实例详解

程序员文章站 2024-02-22 15:56:04
创建c#串口通信程序之命名空间 system.io.ports命名空间中最重用的是serialport 类。 创建c#串口通信程序之创建serialport 对象 通...

创建c#串口通信程序之命名空间

system.io.ports命名空间中最重用的是serialport 类。

创建c#串口通信程序之创建serialport 对象

通过创建serialport 对象,我们可以在程序中控制串口通信的全过程。

我们将要用到的serialport 类的方法:

readline():从输入缓冲区读一新行的值,如果没有,会返回null
writeline(string):写入输出缓冲
open():打开一个新的串口连接
close():关闭

复制代码 代码如下:

serialport sp = new serialport ();

默认情况下,databits 值是8,stopbits 是1,通信端口是com1。这些都可以在下面的属性中重新设置:

baudrate:串口的波特率
stopbits:每个字节的停止位数量
readtimeout:当读操作没有完成时的停止时间。单位,毫秒
还有不少其它公共属性,自己查阅msdn。

创建c#串口通信程序之串口的硬件知识

 在数据传输的时候,每个字节的数据通过单个的电缆线传输。包包括开始位,数据,结束为。一旦开始位传出,后面就会传数据,可能是5,6,7或8位,就看你的设定了。发送和接收必须设定同样的波特率和数据位数。

创建c#串口通信程序之无猫模式

 没有modem模式的电缆只是简单地交叉传送和接收线。同样dtr & dsr, 和 rts & cts也需要交叉。这里,我们三条线。互连2和3(一段的2pin连接3pin),连接两端的5pin。

创建c#串口通信程序示例程序

 如果想使用默认属性,按“save status”按钮,如果想改变属性按“property”。设定好之后,可以通信了。

主窗口的代码

复制代码 代码如下:

#region using directives 

using system; 
using system.collections.generic; 
using system.componentmodel; 
using system.data; 
using system.drawing; 
using system.windows.forms; 
using system.io.ports; 

#endregion 
namespace serialexpample
{
    partial class form1 : form
    {
        //create instance of property page 
        //property page is used to set values for stop bits and 
        //baud rate 
        propertypage pp = new propertypage();
        //create an serial port object 
        serialport sp = new serialport();
        public form1()
        {
            initializecomponent();
        }

        private void propertybutton_click(object sender, eventargs e)
        {
            //show property dialog 
            pp.showdialog();
            propertybutton.hide();
        }

        private void sendbutton_click(object sender, eventargs e)
        {
            try
            {
                //write line to serial port 
                sp.writeline(textbox.text);
                //clear the text box 
                textbox.text = "";
            }
            catch (system.exception ex)
            {
                baudratellabel.text = ex.message;
            }

        }

        private void readbutton_click(object sender, eventargs e)
        {
            try
            {
                //clear the text box 
                textbox.text = "";
                //read serial port and displayed the data in text box 
                textbox.text = sp.readline();
            }
            catch (system.exception ex)
            {
                baudratellabel.text = ex.message;
            }
        }

        private void form1_load(object sender, eventargs e)
        {

        }

        private void form1_formclosing(object sender, formclosingeventargs e)
        {
            messagebox.show("do u want to close the app");
            sp.close();
        }

        private void startcommbutton_click(object sender, eventargs e)
        {
            startcommbutton.hide();
            sendbutton.show();
            readbutton.show();
            textbox.show();
        }

        //when we want to save the status(value) 
        private void savestatusbutton_click_1(object sender, eventargs e)
        {
            //display values 
            //if no property is set the default values 
            if (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;
            }  //创建c#串口通信程序

            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
            {
                //open serial port 
                sp.open();
                //set read time out to 500 ms 
                sp.readtimeout = 500;
            }
            catch (system.exception ex)
            {
                baudratellabel.text = ex.message;
            }
        }
    }
}

创建c#串口通信程序之属性设置对话框代码:

复制代码 代码如下:

#region using directives 
using system; 
using system.collections.generic; 
using system.componentmodel; 
using system.data; 
using system.drawing; 
using system.text; 
using system.windows.forms; 

#endregion 
namespace serialexpample
{
    partial class propertypage : form
    {
        //variables for storing values of baud rate and stop bits 
        private string baudr = "";
        private string stopb = "";

        //property for setting and getting baud rate and stop bits 
        public string brate
        {
            get
            {
                return baudr;
            }
            set
            {
                baudr = value;
            }
        }

        public string sbits
        {
            get
            {
                return stopb;
            }
            set
            {
                stopb = value;
            }
        }

        public propertypage()
        {
            initializecomponent();
        }

        private void cancelbutton_click(object sender, eventargs e)
        {
            this.brate = "";
            this.sbits = "";
            //close form 
            this.close();
        }

        private void okbutton_click_1(object sender, eventargs e)
        {
            //here we set the value for stop bits and baud rate. 
            this.brate = baudratecombobox.text;
            this.sbits = stopbitcombobox.text;
            // 
            this.close();
        }
    }
}

c#串口通信程序创建的相关内容就向你介绍到这里,希望对你了解创建c#串口通信程序的步骤和需要注意的事宜。