串口调试助手中将TextBox中的输入转为十六进制发给串口助手

本周在一个上位机项目中需要将TextBox中的输入转为十六进制发给串口助手,添加一个TextBox,一个Button,一个SerialPort后在VS2017中调试通过,以下直接贴代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPort
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] SendBytes = null;
            string SendData = textBox1.Text;
            SendData = SendData.Replace(" ", "");
            //每两个字符组成一个字节放入
            List<string> SendDataList = new List<string>();
            for (int i = 0; i < SendData.Length; i = i + 2)
            {
                SendDataList.Add(SendData.Substring(i, 2));
            }
            SendBytes = new byte[SendDataList.Count];
            for (int j = 0; j < SendBytes.Length; j++)
            {
                SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
            }
            serialPort1.Write(SendBytes, 0, SendBytes.Length);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章