C# winfrom 串口连接处理数据

主窗体:

  public SerialPortClient portClient = new SerialPortClient();

  private void FrmMain_Load(object sender, EventArgs e)
  {
        InitCmb();
        InitPort();
  }

  private void InitCmb()
  {
         // 绑定端口号
         portClient.PortName = Port;
         //波特率
         portClient.BaudRate = (BaudRates)Enum.Parse(typeof(BaudRates), BaudRate);
         //数据位
         portClient.DataBits = (DataBits)Enum.Parse(typeof(DataBits), DataBits);
         //校验位
         portClient.Parity = (Parity)Enum.Parse(typeof(Parity), Parity1 == "奇校验" ? "1" : Parity1 == "偶校验" ? "2" : "0");
         //停止位
         portClient.StopBits = (StopBits)Enum.Parse(typeof(StopBits), StopBit);
  }

  private void InitPort()
  {
         portClient.DataReceived += new Action<List<byte>>(datapool =>
         {
                while (true)
                {
                    if (datapool.Count < 4) break;
                    if ((datapool[0] == 0x7B))
                    {
                        datapool.RemoveAt(0);
                        continue;
                    }
                    int index = -1;//正确作法是记住上次最末尾的索引,避免重复匹配
                    for (int i = 0; i < datapool.Count - 1; i++)
                    {
                        if (datapool[i] == 0x7D)
                        {
                            index = i;
                            break;
                        }
                    }
                    if (index != -1)
                    {
                        try
                        {
                            byte[] data = datapool.GetRange(0, index).ToArray();
                            datapool.RemoveRange(0, index + 2);
                            string msg = Encoding.UTF8.GetString(data, 0, data.Length);
                        }
                        catch (Exception ex)
                        {

                        }

                    }
                    else break;
                }
        });
   }


    private void button1_Click(object sender, EventArgs e)
    {
         logicForDD.portClient.Open();
    }

    private void button2_Click(object sender, EventArgs e)
    {
         logicForDD.portClient.Close();
    }
    

  

SerialPortClient类:

    public class SerialPortClient
    {
        #region 静态方法
        /// <summary>
        /// 设置串口号
        /// </summary>
        /// <param name="obj">需要绑定的项的集合(如:ComboBox中项的集合ComboBox.Items)</param>
        public static void SetPortNameValues(IList obj)
        {
            obj.Clear();
            try
            {
                foreach (string str in SerialPort.GetPortNames())
                {
                    obj.Add(str);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("未能查询到串口名称——" + e.ToString());
            }

        }

        /// <summary>
        /// 设置波特率
        /// </summary>
        /// <param name="obj">需要绑定的项的集合(如:ComboBox中项的集合ComboBox.Items)</param>
        public static void SetBauRateValues(IList obj)
        {
            obj.Clear();
            foreach (BaudRates rate in Enum.GetValues(typeof(BaudRates)))
            {
                obj.Add(((int)rate).ToString());
            }
        }

        /// <summary>
        /// 设置数据位
        /// </summary>
        /// <param name="obj">需要绑定的项的集合(如:ComboBox中项的集合ComboBox.Items)</param>
        public static void SetDataBitsValues(IList obj)
        {
            obj.Clear();
            foreach (DataBits databit in Enum.GetValues(typeof(DataBits)))
            {
                obj.Add(((int)databit).ToString());
            }
        }

        /// <summary>
        /// 设置校验位列表
        /// </summary>
        /// <param name="obj">需要绑定的项的集合(如:ComboBox中项的集合ComboBox.Items)</param>
        public static void SetParityValues(IList obj)
        {
            obj.Clear();
            foreach (string str in Enum.GetNames(typeof(Parity)))
            {
                obj.Add(str);
            }
        }

        /// <summary>
        /// 设置停止位
        /// </summary>
        /// <param name="obj">需要绑定的项的集合(如:ComboBox中项的集合ComboBox.Items)</param>
        public static void SetStopBitValues(IList obj)
        {
            obj.Clear();
            foreach (string str in Enum.GetNames(typeof(StopBits)))
            {
                obj.Add(str);
            }
        }
        #endregion

        #region 变量属性
        public event Action<List<byte>> DataReceived;
        public event SerialErrorReceivedEventHandler ErrorReceived;

        private SerialPort comPort = new SerialPort();
        private string portName = "COM1";//串口号,默认COM1
        private BaudRates baudRate = BaudRates.BR_9600;//波特率
        private Parity parity = Parity.None;//校验位
        private StopBits stopBits = StopBits.One;//停止位
        private DataBits dataBits = DataBits.Eight;//数据位        

        /// <summary>
        /// 串口号
        /// </summary>
        public string PortName
        {
            get { return portName; }
            set { portName = value; }
        }

        /// <summary>
        /// 波特率
        /// </summary>
        public BaudRates BaudRate
        {
            get { return baudRate; }
            set { baudRate = value; }
        }

        /// <summary>
        /// 奇偶校验位
        /// </summary>
        public Parity Parity
        {
            get { return parity; }
            set { parity = value; }
        }

        /// <summary>
        /// 数据位
        /// </summary>
        public DataBits DataBits
        {
            get { return dataBits; }
            set { dataBits = value; }
        }

        /// <summary>
        /// 停止位
        /// </summary>
        public StopBits StopBits
        {
            get { return stopBits; }
            set { stopBits = value; }
        }
        #endregion

        #region 构造函数
        /// <summary>
        /// 无参构造函数
        /// </summary>
        public SerialPortClient()
        {
            BoundEvents();
        }

        void BoundEvents()
        {
            comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
            comPort.ErrorReceived += new SerialErrorReceivedEventHandler(comPort_ErrorReceived);
        }

        /// <summary>
        /// 参数构造函数(使用枚举参数构造)
        /// </summary>
        /// <param name="baud">波特率</param>
        /// <param name="par">奇偶校验位</param>
        /// <param name="sBits">停止位</param>
        /// <param name="dBits">数据位</param>
        /// <param name="name">串口号</param>
        public SerialPortClient(string name, BaudRates baud, Parity par, DataBits dBits, StopBits sBits)
        {
            this.portName = name;
            this.baudRate = baud;
            this.parity = par;
            this.dataBits = dBits;
            this.stopBits = sBits;
            BoundEvents();
        }

        /// <summary>
        /// 参数构造函数(使用字符串参数构造)
        /// </summary>
        /// <param name="baud">波特率</param>
        /// <param name="par">奇偶校验位</param>
        /// <param name="sBits">停止位</param>
        /// <param name="dBits">数据位</param>
        /// <param name="name">串口号</param>
        public SerialPortClient(string name, string baud, string par, string dBits, string sBits)
        {
            this.portName = name;
            this.baudRate = (BaudRates)Enum.Parse(typeof(BaudRates), baud);
            this.parity = (Parity)Enum.Parse(typeof(Parity), par);
            this.dataBits = (DataBits)Enum.Parse(typeof(DataBits), dBits);
            this.stopBits = (StopBits)Enum.Parse(typeof(StopBits), sBits);
            BoundEvents();
        }
        #endregion

        #region 事件处理函数
        /// <summary>
        /// 数据仓库
        /// </summary>
        List<byte> datapool = new List<byte>();//存放接收的所有字节
        /// <summary>
        /// 数据接收处理
        /// </summary>
        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (comPort.IsOpen)     //判断是否打开串口
            {

                Byte[] receivedData = new Byte[comPort.BytesToRead];        //创建接收字节数组
                comPort.Read(receivedData, 0, receivedData.Length);         //读取数据

                //触发整条记录的处理
                if (DataReceived != null)
                {
                    datapool.AddRange(receivedData);
                    DataReceived(datapool);
                }

            }
            else
            {
                Console.WriteLine("请打开某个串口", "Error");
            }
        }
        /// <summary>
        /// 错误处理函数
        /// </summary>
        void comPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            if (ErrorReceived != null)
            {
                ErrorReceived(sender, e);
            }
        }
        #endregion

        #region 串口关闭/打开
        /// <summary>
        /// 端口是否已经打开
        /// </summary>
        public bool IsOpen
        {
            get
            {
                return comPort.IsOpen;
            }
        }

        /// <summary>
        /// 打开端口
        /// </summary>
        /// <returns></returns>
        public void Open()
        {
            if (comPort.IsOpen) comPort.Close();

            comPort.PortName = portName;
            comPort.BaudRate = (int)baudRate;
            comPort.Parity = parity;
            comPort.DataBits = (int)dataBits;
            comPort.StopBits = stopBits;

            comPort.Open();
        }

        /// <summary>
        /// 关闭端口
        /// </summary>
        public void Close()
        {
            if (comPort.IsOpen) comPort.Close();
        }

        /// <summary>
        /// 丢弃来自串行驱动程序的接收和发送缓冲区的数据
        /// </summary>
        public void DiscardBuffer()
        {
            comPort.DiscardInBuffer();
            comPort.DiscardOutBuffer();
        }
        #endregion

        #region 写入数据
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="buffer"></param>
        public void Write(byte[] buffer, int offset, int count)
        {
            if (!(comPort.IsOpen)) comPort.Open();
            comPort.Write(buffer, offset, count);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="buffer">写入端口的字节数组</param>
        public void Write(byte[] buffer)
        {
            if (!(comPort.IsOpen)) comPort.Open();
            comPort.Write(buffer, 0, buffer.Length);
        }
        #endregion
    }

    #region 波特率、数据位的枚举
    /// <summary>
    /// 串口数据位列表(5,6,7,8)
    /// </summary>
    public enum DataBits : int
    {
        Five = 5,
        Six = 6,
        Sevent = 7,
        Eight = 8
    }

    /// <summary>
    /// 串口波特率列表。
    /// 75,110,150,300,600,1200,2400,4800,9600,14400,19200,28800,38400,56000,57600,
    /// 115200,128000,230400,256000
    /// </summary>
    public enum BaudRates : int
    {
        BR_75 = 75,
        BR_110 = 110,
        BR_150 = 150,
        BR_300 = 300,
        BR_600 = 600,
        BR_1200 = 1200,
        BR_2400 = 2400,
        BR_4800 = 4800,
        BR_9600 = 9600,
        BR_14400 = 14400,
        BR_19200 = 19200,
        BR_28800 = 28800,
        BR_38400 = 38400,
        BR_56000 = 56000,
        BR_57600 = 57600,
        BR_115200 = 115200,
        BR_128000 = 128000,
        BR_230400 = 230400,
        BR_256000 = 256000
    }
    #endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值