日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

c#serialport類實現(xiàn)串口通信的源代碼

 orion360doc 2011-01-14
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>
        /// 必需的設(shè)計器變量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設(shè)計器生成的代碼

        /// <summary>
        /// 設(shè)計器支持所需的方法 - 不要
        /// 使用代碼編輯器修改此方法的內(nèi)容。
        /// </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 = "發(fā)送";
            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 = "發(fā)送";
            //
            // 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)
        {
            //實例化串口對象(默認(rèn):COMM1,9600,e,8,1)            
            SerialPort serialPort1 = new SerialPort();
            //更改參數(shù)
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 19200;
            serialPort1.Parity = Parity.Odd;
            serialPort1.StopBits = StopBits.Two;

            //上述步驟可以用在實例化時調(diào)用SerialPort類的重載構(gòu)造函數(shù)
            //SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two);

            //打開串口(打開串口后不能修改端口名,波特率等參數(shù),修改參數(shù)要在串口關(guān)閉后修改)
            serialPort1.Open();

            //發(fā)送數(shù)據(jù)
            SendStringData(serialPort1);
            //也可用字節(jié)的形式發(fā)送數(shù)據(jù)
            //SendBytesData(serialPort1);
            
            //開啟接收數(shù)據(jù)線程
            ReceiveData(serialPort1);
            
        }

        

        //發(fā)送字符串?dāng)?shù)據(jù)
        private void SendStringData(SerialPort serialPort)
        {
            serialPort.Write(txtSend.Text);
        }

        /// <summary>
        /// 開啟接收數(shù)據(jù)線程
        /// </summary>
        private void ReceiveData(SerialPort serialPort)
        {
            //同步阻塞接收數(shù)據(jù)線程
            Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData));
            threadReceive.Start(serialPort);
            
             //也可用異步接收數(shù)據(jù)線程
            //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
            //threadReceiveSub.Start(serialPort);
            
        }

        //發(fā)送二進(jìn)制數(shù)據(jù)
        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
            {
                //阻塞到讀取數(shù)據(jù)或超時(這里為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 = 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>
        /// 應(yīng)用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmTESTSerialPort());
        }
    }

}

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多