c# 串口数据接收

串口数据:

接收:

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();
        }
发现自己的不足,善于利用找到的方法去扬长避短。行动起来。
原文地址:https://www.cnblogs.com/rechen/p/5078161.html