基於.Net C# 通信開發-串口調試助手

  基於.Net C# 通信開發-串口調試助手

 

  1、概述

  

  串口調試助手,廣泛應用於工控領域的數據監控、數據採集、數據分析等工作,可以幫助串口應用設計、開發、測試人員檢查所開發的串口應用軟硬件的數據收發狀況,提高開發的速度,成爲您的串口應用的開發助手。
實全串口調試助手是綠色軟件,只有一個執行文件,適用於各版本Windows操作系統,基於C# .Net 4.0 框架開發。可以在一臺PC上同時啓動多個串口調試助手(使用不同的COM口)。
  典型應用場合:通過串口調試助手與自行開發的串口程序或者串口設備進行通信聯調。
  支持多串口,自動監測枚舉本地可用串口;自由設置串口號、波特率、校驗位、數據位和停止位等(支持自定義非標準波特率);
  支持ASCII/Hex兩種模式的數據收發,發送和接收的數據可以UTF-8、16進制和AscII碼之間任意轉換;
  支持間隔發送,循環發送,批處理髮送,輸入數據可以從外部文件導入。

  串口調試開發,一般分爲讀取電腦連接串口信息、選擇串口信息進行連接、設置相關發送接收配置、發送命令或消息,接收讀取返回結果。

 

  2、串口開發主要代碼

  2.1、讀取電腦連接串口信息

  串口調試,首先需要程序讀取電腦連接串口信息。

  //讀取連接串口
            string[] mPortNames = SerialPort.GetPortNames();
            this.txtPortName.Items.Clear();
            foreach (var item in mPortNames)
            {
                this.txtPortName.Items.Add(item);
            }

            this.txtParity.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(Parity)))
            {
                this.txtParity.Items.Add(item);
            }
            this.txtParity.DropDownStyle = ComboBoxStyle.DropDownList;

            this.txtStopBits.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(StopBits)))
            {
                this.txtStopBits.Items.Add(item);
            }
            this.txtStopBits.DropDownStyle = ComboBoxStyle.DropDownList;

            this.txtHandshake.Items.Clear();
            foreach (string item in Enum.GetNames(typeof(Handshake)))
            {
                this.txtHandshake.Items.Add(item);
            }
            this.txtHandshake.DropDownStyle = ComboBoxStyle.DropDownList;

  2.2、選擇串口信息進行連接

/// <summary>
        /// 獲取串口信息
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="fail"></param>
        /// <returns></returns>
        public static SerialPort GetSerialPort(SerialPortSet setting, out string fail)
        {
            fail = string.Empty;
            try
            {
                _SerialPort = new SerialPort();
                _SerialPort.PortName = setting.PortName;
                _SerialPort.BaudRate = setting.BaudRate.ToInt32();
                _SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), setting.Parity, true);
                _SerialPort.DataBits = setting.DataBits.ToInt32();
                _SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), setting.StopBits, true);
                _SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), setting.Handshake, true);

                return _SerialPort;
            }
            catch (Exception ex)
            {
                fail = "打開串口 異常:" + ex.Message;
                return null;
            }
        }

  2.3、選擇相關發送接收配置

  支持UTF-8、ASCII、GB2312、16進制內容,收、發選擇;支持間隔發送,循環發送,批處理髮送,輸入數據可以從外部文件導入。

 

  2.4、發送命令或消息

/// <summary>
        /// 發送命令或消息
        /// </summary>
        /// <param name="content"></param>
        private void SendByte(string content)
        {
            try
            {
                if (this.ckbShowSend.Checked)
                    this.AppendText(content);

                byte[] buffer;
                if (this.txtSendEncoding.Text.Length <= 0)
                    buffer = Encoding.Default.GetBytes(this.txtContent.Text);
                else if (this.txtSendEncoding.Text == "16進制")
                    buffer = this.HexToByte(this.txtContent.Text);
                else
                    buffer = Encoding.GetEncoding(this.txtSendEncoding.Text).GetBytes(this.txtContent.Text);
                //向串口發送數據
                this._SerialPort.Write(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {
                WinMessageBox.Warning("發送失敗:" + ex.Message);
            }
        }

 

  2.5、接收讀取返回結果

/// <summary>
        /// 接收讀取返回結果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] buffer = new byte[this._SerialPort.ReadBufferSize];
            int count = this._SerialPort.Read(buffer, 0, buffer.Length);
            //string str = Encoding.Default.GetString(readBuffer).TrimEnd('\0');
            if (this.txtEncoding.Text.Length <= 0)
                this.AppendText(System.Text.Encoding.Default.GetString(buffer,0, count));
            else if (this.txtEncoding.Text == "16進制")
                this.AppendText(this.ByteToHex(buffer,0,count));
            else
                this.AppendText(System.Text.Encoding.GetEncoding(this.txtEncoding.Text).GetString(buffer,0,count));
        }

 

  3、結語

  至此介紹完畢,本項目開源,源碼地址:https://gitee.com/ShiQuan25/SerialHelper 

  安裝包下載地址:https://gitee.com/ShiQuan25/SerialHelper/attach_files/1048876/download/ShiQuan.SerialHelper.zip

  不當之處,歡迎指正!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章