码迷,mamicode.com
首页 > Windows程序 > 详细

c# 串口发送接收数据

时间:2015-03-18 23:06:45      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

   /********************** 串口数据接收事件 *****************************/
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            UTF8Encoding uTF8Encoding = new UTF8Encoding();
            byte[] readBytes = new byte[this.SerialPort.BytesToRead];
            int num = this.SerialPort.Read(readBytes, 0, readBytes.Length);
            this.builder.Clear();//清空缓存
            this.received_count += (long)num;//加接收计数
            this.rxtextBox.Invoke((EventHandler)delegate
            {
                if (!this.rxcharSetup.Checked)//判断接收数据的格式
                {                   //获取字符长度
                    for (int i = 0; i < readBytes.Length; i++)
                    {
                        byte b = readBytes[i];//显示十六进制
                        this.builder.Append("0x" + b.ToString("X2") + " ");
                    }
                }
                else
                {   //显示字符格式
                    this.builder.Append(Encoding.GetEncoding("GB2312").GetString(readBytes));
                }
                this.rxtextBox.SelectionStart = this.rxtextBox.TextLength;
                this.rxtextBox.AppendText(this.builder.ToString());
                this.rxnumdata.Text = "Rx " + this.received_count.ToString();
                //更新发送计数
            });
        }
  /********************** 发送按钮 *****************************/
        private void senddata_Click(object sender, EventArgs e)
        {
            if (!this.SerialPort.IsOpen)
            {
                MessageBox.Show("串口未打开!!!", "警告");
            }
            else
            {
                int num;
                if (this.txdataSetup.Checked)
                {
                    MatchCollection matchCollection = Regex.Matches(this.txtextBox.Text, "(?i)[\\da-f]{2}");
                    List<byte> list = new List<byte>();
                    foreach (Match match in matchCollection)
                    {
                        list.Add(byte.Parse(match.Value, NumberStyles.HexNumber));
                    }
                    this.SerialPort.Write(list.ToArray(), 0, list.Count);
                    num = list.Count;
                }
                else
                {
                    this.SerialPort.WriteLine(this.txtextBox.Text);
                    num = this.txtextBox.Text.Length + 2;
                }
                this.send_count += (long)num;
                this.txnumdata.Text = "Tx " + this.send_count.ToString();
                //更新接收计数
            }
        }

 

c# 串口发送接收数据

标签:

原文地址:http://www.cnblogs.com/mrqiang/p/4348721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!