A-A+

C# SerialportHelper 串口通信 实例

2015年03月22日 C# 评论 1 条 阅读 4,321 views 次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Text.RegularExpressions;

namespace testEmgucv
{
    class SerialPortHelper
    {
        private long _receiveByteCount = 0, _sendByteOfCount = 0;


        public long ReceiveByteCount { get { return _receiveByteCount; } 
        set { _receiveByteCount = value; } }
        public long SendByteOfCount { get { return _sendByteOfCount; } 
        set { _sendByteOfCount = value; } }


        SerialPort _serialPort = new SerialPort();


        private DataReceived _received = null;


        public delegate void DataReceived(byte[] data);


        public bool IsOpen { get { return _serialPort.IsOpen; } }


        public static string[] SerialPortNames
        {
            get
            {
                string[] serialports = SerialPort.GetPortNames();
                Array.Sort(serialports, new Comparison<string>(
                  delegate(string x, string y)
                  {
                      if (x.Length > 3 && y.Length > 3)
                      {
                          string index1 = x.Substring(3);
                          string index2 = y.Substring(3);
                          try
                          {
                              int n1 = Convert.ToInt32(index1);
                              int n2 = Convert.ToInt32(index2);
                              return n1 - n2;
                          }
                          catch
                          {
                          }
                      }
                      return 0;
                  }));
                return serialports;
            }
        }


        public SerialPortHelper(DataReceived received)
        {
            _received = received;
            _serialPort.NewLine = "\r\n";
            _serialPort.DataReceived += delegate
            {
                System.Threading.Thread.Sleep(50);
                int ReadLength = _serialPort.BytesToRead;
                if (ReadLength > 0)
                {
                    _receiveByteCount += ReadLength;
                    byte[] ReadBuffer = new byte[ReadLength];
                    _serialPort.Read(ReadBuffer, 0, ReadLength);
                    if (_received != null)
                    {
                        _received(ReadBuffer);
                    }
                }
            };
        }


        public bool Open(string PortName,int BaudRate)
        {
            try
            {
                _serialPort.PortName = PortName;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.DataBits = 8;
                _serialPort.BaudRate = BaudRate;
                _serialPort.Open();
            }
            catch (Exception ex)
            {
                //输入日志
                return false;
            }

            return true;
        }

        /// <summary>
        /// 打开串口,波特率默认9600
        /// </summary>
        /// <param name="PortName"></param>
        /// <returns></returns>
        public bool Open(string PortName)
        {
            try
            {
                _serialPort.PortName = PortName;
                _serialPort.StopBits = StopBits.One;
                _serialPort.Parity = Parity.None;
                _serialPort.DataBits = 8;
                _serialPort.BaudRate = 9600;
                _serialPort.Open();
            }
            catch (Exception ex)
            {
                //输入日志
                return false;
            }
            return true;
        }


        public void Close()
        {
            _serialPort.Close();
        }

        public void WriteLine(string text)
        {
            if (_serialPort.IsOpen)
            {
                _sendByteOfCount += text.Length;
                _serialPort.WriteLine(text);
            }
        }

        public void Write(byte[] buffer)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Write(buffer, 0, buffer.Length);
                _sendByteOfCount += buffer.Length;
            }
        }

        public void WriteLine16(string text)
        {
            if (_serialPort.IsOpen)
            {
                //我们不管规则了。如果写错了一些,我们允许的,只用正则得到有效的十六进制数
                MatchCollection mc = Regex.Matches(text, @"(?i)[\da-f]{2}");
                List<byte> buf = new List<byte>();//填充到这个临时列表中
                //依次添加到列表中
                foreach (Match m in mc)
                {
                    //buf.Add(byte.Parse(m.Value));
                    buf.Add(byte.Parse(m.Value, System.Globalization.NumberStyles.HexNumber));
                }
                //转换列表为数组后发送
                _serialPort.Write(buf.ToArray(), 0, buf.Count);
                //记录发送的字节数
                _sendByteOfCount += buf.Count;

                buf = null;
                mc = null;

            }

        }


    }
}


调用方法:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace SerialnumPort1
{
    public partial class Form1 : Form
    {
        string _tempfile = AppDomain.CurrentDomain.BaseDirectory + "temp.data";
        SerialPortHelper _helper = null;
        public Form1()
        {
            InitializeComponent();
            _helper = new SerialPortHelper(delegate(byte[] data)
            {
                this.Invoke(
                 (EventHandler)delegate
                 {
                     if (checkBox2.Checked)
                     {
                         using (System.IO.FileStream fs = 
                         new System.IO.FileStream(_tempfile, System.IO.FileMode.Append))
                         {
                             fs.Write(data, 0, data.Length);
                         }
                     }

                     StringBuilder readStr = new StringBuilder();
                     foreach (byte b in data)
                     {
                         string temp = string.Format("{0:X2} ", b);
                         readStr.Append(temp);
                     }
                     readStr.Append("已接收\r\n");

                     toolStripStatusLabel1.Text = "已接收字节数:" + _helper.ReceiveByteCount;
                     richTextBox1.AppendText(readStr.ToString());
                     richTextBox1.ScrollToCaret();
                 }
                );
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] serialnums = SerialPortHelper.SerialPortNames;
            comboBox1.Items.AddRange(serialnums);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if ("打开" == button2.Text)
            {
                try
                {
                    _helper.Open(comboBox1.Text);
                    button2.Text = "关闭";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
                }
            }
            else
            {
                button2.Text = "打开";
                _helper.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_helper.IsOpen)
            {
                if (!checkBox1.Checked)
                {
                    _helper.WriteLine(textBox1.Text);
                }
                else
                {
                    string sendtext = textBox1.Text.TrimEnd(' ');
                    string[] sps = sendtext.Split(' ');
                    byte[] sendata = new byte[sps.Length];
                    for (int i = 0; i < sendata.Length; ++i)
                    {
                        sendata[i] = (byte)Convert.ToInt32(sps[i], 16);
                    }
                    _helper.Write(sendata);
                }
                richTextBox1.AppendText(textBox1.Text + " 已发送\r\n");
                richTextBox1.ScrollToCaret();
                toolStripStatusLabel2.Text = "已发送字节数:" + _helper.SendByteOfCount;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
            {
                System.IO.File.Delete(_tempfile);
                using (System.IO.FileStream fs = System.IO.File.Create(_tempfile))
                {
                }
            }
        }

    }
}



1 条留言  访客:1 条  博主:0 条

  1. C#学习

    文章确实不错,很实用

评论已关闭!

Copyright © sql语句大全 保留所有权利.   Theme  Ality 津ICP备15000635号

用户登录

分享到: