SerialPort同步和异步数据读取

来源:互联网 发布:重庆搜索引擎优化公司 编辑:程序博客网 时间:2024/04/28 18:19

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace TestSerialPort
{
    public partial class frmTESTSerialPort : Form
    {
        public frmTESTSerialPort()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private Button button1;
        private TextBox txtSend;
        private TextBox txtReceive;
        private Label label1;
        private Label label2;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.txtSend = new System.Windows.Forms.TextBox();
            this.txtReceive = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(440, 379);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "发送";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // txtSend
            //
            this.txtSend.Location = new System.Drawing.Point(59, 12);
            this.txtSend.Multiline = true;
            this.txtSend.Name = "txtSend";
            this.txtSend.Size = new System.Drawing.Size(456, 164);
            this.txtSend.TabIndex = 2;
            //
            // txtReceive
            //
            this.txtReceive.Location = new System.Drawing.Point(59, 200);
            this.txtReceive.Multiline = true;
            this.txtReceive.Name = "txtReceive";
            this.txtReceive.Size = new System.Drawing.Size(456, 164);
            this.txtReceive.TabIndex = 2;
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(13, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "发送";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(13, 213);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(41, 12);
            this.label2.TabIndex = 0;
            this.label2.Text = "接收";
            //
            // frmTESTSerialPort
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(546, 434);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtReceive);
            this.Controls.Add(this.txtSend);
            this.Controls.Add(this.button1);
            this.Name = "frmTESTSerialPort";
            this.Text = "串口试验";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            //实例化串口对象(默认:COMM1,9600,e,8,1)           
            SerialPort serialPort1 = new SerialPort();
            //更改参数
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 19200;
            serialPort1.Parity = Parity.Odd;
            serialPort1.StopBits = StopBits.Two;

            //上述步骤可以用在实例化时调用SerialPort类的重载构造函数
            //SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two);

            //打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改)
            serialPort1.Open();

            //发送数据
            SendStringData(serialPort1);
            //也可用字节的形式发送数据
            //SendBytesData(serialPort1);
           
            //开启接收数据线程
            ReceiveData(serialPort1);
           
        }

       

        //发送字符串数据
        private void SendStringData(SerialPort serialPort)
        {
            serialPort.Write(txtSend.Text);
        }

        /// <summary>
        /// 开启接收数据线程
        /// </summary>
        private void ReceiveData(SerialPort serialPort)
        {
            //同步阻塞接收数据线程
            Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData));
            threadReceive.Start(serialPort);
           
             //也可用异步接收数据线程
            //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
            //threadReceiveSub.Start(serialPort);
           
        }

        //发送二进制数据
        private void SendBytesData(SerialPort serialPort)
        {
            byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text );
            serialPort.Write(bytesSend, 0, bytesSend.Length);
        }

        //同步阻塞读取
        private void SynReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            System.Threading.Thread.Sleep(0);
            serialPort.ReadTimeout = 1000;
            try
            {
                //阻塞到读取数据或超时(这里为2秒)
                byte firstByte=Convert.ToByte(serialPort.ReadByte());
                int bytesRead=serialPort.BytesToRead ;               
                byte[] bytesData=new byte[bytesRead+1];
                bytesData[0] = firstByte;
                for (int i = 1; i <=bytesRead; i++)
                    bytesData[i] = Convert.ToByte( serialPort.ReadByte());
                txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                //处理超时错误
            }
           
            serialPort.Close();

        }

        //异步读取
        private void AsyReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            System.Threading.Thread.Sleep(500);
            try
            {
                 txtReceive.Text =   serialPort.ReadExisting();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //处理错误
            }
            serialPort.Close();
        }

    }


    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmTESTSerialPort());
        }
    }

}

 

 

三.SerialPort的使用
对于熟悉MSComm控件的程序设计者,SerialPort类是相当容易上手的。在进行串口通讯时,一般的流程是设置通讯端口号及波特率、数据位、停止位和校验位,再打开端口连接,发送数据,接收数据,最后关闭端口连接这样几个步骤。
数据接收的设计方法在这里比较重要,采用轮询的方法比较浪费时间,在Visual Basic中的延时方法中一般会调用API并用DOEvents方法来处理,但程序不易控制,建议采用DataReceived事件触发的方法,合理的设置ReceivedBytesThreshold的值,若接收的是定长的数据,则将ReceivedBytesThreshold设为接收数据的长度,若接收数据的结尾是固定的字符或字符串则可采用ReadTo的方法或在DataReceived事件中判断接收的字符是否满足条件
SerialPort类读取数据的许多方法是同步阻塞调用,尽量避免在主线程中调用,可以使用异步处理或线程间处理调用这些读取数据的方法。
由于DataReceived事件在辅线程被引发,当收到完整的一条数据,返回主线程处理或在窗体上显示时,请注意跨线程的处理,C#可采用控件异步委托的方法Control.BeginInvoke及同步委托的方法Invoke
 
四.结束语
.NET平台下熟练使用SerialPort 类,可以很好地开发出串口通讯类程序,对于过去使用MSComm控件设计了一些通讯程序,也可以将MSComm控件替换为SerialPort类,当然为了避免对以前的项目做大的改动,可以使用SerialPort类设计一些与MSComm控件具有相同接口的类,在今后工业控制中,SerialPort类将广泛地应用于串口通讯程序的设计中,发挥着与MSComm控件一样的作用。