串口调试:十六进制发送和显示

发送十六进制

        private void btnSend_Click(object sender, EventArgs e)
        {
            string hexString = tboxSend.Text.Trim();
            int len = hexString.Length / 2;           
            char[] chars = hexString.ToCharArray();
            string[] hexes = new string[len];
            byte[] bytes = new byte[len];
            for (int i = 0, j = 0; j < len; i = i + 2, j++)
            {
                hexes[j] = "" + chars[i] + chars[i + 1];
                bytes[j] = (byte)(Convert.ToInt16(hexes[j], 16));
            }
            //port.Write(tboxSend.Text.Trim());
            port.Write(bytes, 0, len);
        }

接收后显示为十六进制

        private delegate void SafeWinFormsThreadDelegate(string msg);

        private void WriteMsg(string msg)
        {
            SafeWinFormsThreadDelegate d = new SafeWinFormsThreadDelegate(UpdateUI);
            Invoke(d, new object[] { msg });
        }
        private void UpdateUI(string msg)
        {
            this.tboxRec.Text = msg;
        }

        private void btnRec_Click(object sender, EventArgs e)
        {
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            btnRec.Enabled = false;
        }

        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)   
        {   
            int rsLength = 0;   
            bool loop=true;               
            strBuilder.Remove(0, strBuilder.Length);
            while (loop)
            {
                if (port.BytesToRead == rsLength)
                {
                    loop = false;
                }
                else
                {
                    rsLength = port.BytesToRead;
                }
                //Thread.Sleep(100);
            }
            byte[] buf = new byte[rsLength];
            port.Read(buf, 0, rsLength);
            foreach (byte b in buf)
            {
                string hex = b.ToString("x").ToUpper();
                hex = (hex.Length == 1) ? "0" + hex : hex;
                strBuilder.Append(hex + " ");
            }
            string result = strBuilder.ToString();
            WriteMsg(result);   
        }

 

你可能感兴趣的:(J#,thread)