c# SerialPort 串口通讯 十六进制接收发送 转换

 SerialPort serialPort1 = new SerialPort();
        public Form1()
        {
            InitializeComponent();
            //线程传值
            CheckForIllegalCrossThreadCalls = false;
            serialPort1.DataReceived += serialPort1_DataReceived;
        }
 // false 配置  true读取
        bool bo = false;
 private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {

                Thread.Sleep(50);  //(毫秒)等待一定时间,确保数据的完整性 int len   
                int len = serialPort1.BytesToRead;
                string receivedata = string.Empty;
                int buffersize = 8;   //十六进制数的大小(假设为6byte)
                byte[] buffer = new byte[buffersize];   //创建缓冲区
                if (len != 0)
                {
                    serialPort1.Read(buffer, 0, buffersize);    //从com1读取
                    receivedata = Encoding.Default.GetString(buffer);
                }
                if (receivedata.Trim() != "")
                {


                    string str = byteToHexStr(buffer);

                    if (bo)
                    {
                        textBox1.AppendText("读取返回:" + 
                            "0x" + str.Substring(0, 2) +
                            " 0x" + str.Substring(2, 2) +
                            " 0x" + str.Substring(4, 2) +
                            " 0x" + str.Substring(6, 2) +
                            " 0x" + str.Substring(8, 2) +
                            " 0x" + str.Substring(10, 2) +
                            " 0x" + str.Substring(12, 2) +
                            " 0x" + str.Substring(14, 2) + "\r\n");
                        textBox1.AppendText("读取返回:" + Convert.ToInt32(str.Substring(8, 2), 16)
                         + "." + Convert.ToInt32(str.Substring(10, 2), 16)
                         + "." + Convert.ToInt32(str.Substring(12, 2), 16)
                         + "." + Convert.ToInt32(str.Substring(14, 2), 16) + "\r\n");
                    }
                    else
                    {
                        string s = "55aaaa55" + Ten2Hex(t1.Text) + Ten2Hex(t2.Text).PadLeft(2, '0') + Ten2Hex(t3.Text).PadLeft(2, '0') + Ten2Hex(t4.Text).PadLeft(2, '0');
                        string s1 = "0x55 0xaa 0xaa 0x55" + " 0x" + Ten2Hex(t1.Text) + " 0x" + Ten2Hex(t2.Text).PadLeft(2, '0') + " 0x" + Ten2Hex(t3.Text).PadLeft(2, '0') + " 0x" + Ten2Hex(t4.Text).PadLeft(2, '0');
                        textBox1.AppendText("配置返回:" +
                            "0x" + str.Substring(0, 2) +
                            " 0x" + str.Substring(2, 2) +
                            " 0x" + str.Substring(4, 2) +
                            " 0x" + str.Substring(6, 2) +
                            " 0x" + str.Substring(8, 2) +
                            " 0x" + str.Substring(10, 2) +
                            " 0x" + str.Substring(12, 2) +
                            " 0x" + str.Substring(14, 2) + "\r\n");

                        if (str.ToUpper() == s.ToUpper())
                        {
                            textBox1.AppendText("配置返回:配置成功!" + "\r\n");
                        }
                        else
                        {
                            textBox1.AppendText("配置返回:配置失败!" + "\r\n");
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //获取串口
                String[] portnames = SerialPort.GetPortNames();
                foreach (var item in portnames)
                {
                    comboBox1.Items.Add(item);
                }
                comboBox1.SelectedIndex = 0;
                btn_Send.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        ///窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            serialPort1.Close();
            Environment.Exit(0);
        }
        //打开串口
        public void OpenCom()
        {
            try
            {
                //波特率
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                //数据位
                serialPort1.DataBits = 8;
                serialPort1.PortName = comboBox1.Text;
                //两个停止位
                serialPort1.StopBits = System.IO.Ports.StopBits.One;
                //无奇偶校验位
                serialPort1.Parity = System.IO.Ports.Parity.None;
                serialPort1.ReadTimeout = 100;
                serialPort1.Open();
                if (!serialPort1.IsOpen)
                {
                    MessageBox.Show("端口打开失败");
                    return;
                }
                else
                {
                    this.textBox1.AppendText("端口" + comboBox1.Text + "打开成功\r\n");
                }
                serialPort1.DataReceived += serialPort1_DataReceived;
            }
            catch (Exception ex)
            {
                serialPort1.Dispose();
                textBox1.AppendText(ex.Message + "\r\n");
            }
        }

        private void btn_Open_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();
                    btn_Open.Text = "串口已经关闭";
                    this.textBox1.AppendText("端口" + comboBox1.Text + "关闭成功\r\n");
                    btn_Send.Enabled = false;
                    读取.Enabled = false;

                    comboBox1.Enabled = true;
                    comboBox4.Enabled = true;
                    comboBox5.Enabled = true;
                    comboBox2.Enabled = true;
                    comboBox3.Enabled = true;
                }
                else
                {
                    OpenCom();
                    btn_Open.Text = "串口已经打开";
                    btn_Send.Enabled = true;
                    读取.Enabled = true;

                    comboBox1.Enabled = false;
                    comboBox4.Enabled = false;
                    comboBox5.Enabled = false;
                    comboBox2.Enabled = false;
                    comboBox3.Enabled = false;
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }

///发送  
 this.serialPort1.Write(cher, 0, 8);//发送数据   

转换代码

 /// <summary>
        /// string  转byte
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary>
        /// byte[] 转string
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X").PadLeft(2, '0');
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 从十进制转换到十六进制
        /// </summary>
        /// <param name="ten"></param>
        /// <returns></returns>
        public static string Ten2Hex(string ten)
        {
            ulong tenValue = Convert.ToUInt64(ten);
            ulong divValue, resValue;
            string hex = "";
            do
            {
                //divValue = (ulong)Math.Floor(tenValue / 16);

                divValue = (ulong)Math.Floor((decimal)(tenValue / 16));

                resValue = tenValue % 16;
                hex = tenValue2Char(resValue) + hex;
                tenValue = divValue;
            }
            while (tenValue >= 16);
            if (tenValue != 0)
                hex = tenValue2Char(tenValue) + hex;
            return hex;
        }
        public static string tenValue2Char(ulong ten)
        {
            switch (ten)
            {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                    return ten.ToString();
                case 10:
                    return "A";
                case 11:
                    return "B";
                case 12:
                    return "C";
                case 13:
                    return "D";
                case 14:
                    return "E";
                case 15:
                    return "F";
                default:
                    return "";
            }
        }

连接:https://download.csdn.net/download/qq_36074218/13687697

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页