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

c# 串口数据接收

时间:2015-12-26 16:38:12      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

 

串口数据:

 

接收:

 

public static string aa="";
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string s100 = "";
            System.Threading.Thread.Sleep(100);
            int bytes = serialPort.BytesToRead;
            byte[] buffer = new byte[bytes];
            if (bytes == 0)
            { return; }
            serialPort.Read(buffer, 0, bytes);
            s100 = ww(buffer);//字节数组转为十六进制字符串
            if (s100 != "")
            {

                string s = "";
                int length = Convert.ToInt32( buffer[7].ToString()) - 1;
                for (int j = 9; j < length+9; j++)
                {
                    string a= Convert.ToString(buffer[j],16);
                    if(a.Length==1)
                    {
                        a = "0" + a;
                    }
                    s += a;
                }
                
                //s = "";
               // MessageBox.Show(s100);
                aa = s100;
                InvokeHelper.Set(richTextBox2, "Text", aa);
            }
            serialPort.DiscardInBuffer();

        }

        public string ww(byte[] data)//字节数组转为十六进制字符串
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, 0).PadRight(3,  ));
            return sb.ToString().ToUpper();
        }

 

c# 串口数据接收

标签:

原文地址:http://www.cnblogs.com/rechen/p/5078161.html

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