C#编写的串口调试助手

利用C#编写的串口调试助手,如下图所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;

namespace SerialPort1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private SerialPort comn = new SerialPort();
        private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复创建,定义到外面
        private long received_count = 0;//接收计数
        private long send_count = 0;//发送计数
        private bool Listening = false;//是否没有执行完invoke相关操作
        private bool PortClosing = false;//是否正在关闭串口,执行Application.DoEvents,并组织再次invoke
        //窗口初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化下拉串口名称列表
            String[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            ComboBoxPortName.Items.AddRange(ports);
            ComboBoxPortName.SelectedIndex = ComboBoxPortName.Items.Count > 0 ? 0 : -1;
            ComboBoxBaudrate.SelectedIndex = ComboBoxBaudrate.Items.IndexOf("9600");
            //初始化serialPort对象
            comn.NewLine = "/r/n";
            comn.RtsEnable = true;//根据实际情况决定
            //添加事件注册
            comn.DataReceived += comn_DataReceived;
        }
        void comn_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (PortClosing)
                return;//如果正常关闭,忽略操作,直接返回
            try
            {
                Listening = true;//设置标记,说明我已经开始处理数据,一会儿要使用系统的UI
                int n = comn.BytesToRead;//先记录下来,避免某种原因,认为的原因,操作几次之间时间长短,缓存不一致
                byte[] buf = new byte[n];//声明一个临时数组存储当前的串口数据
                received_count += n;//增加接收计数
                comn.Read(buf, 0, n);//读取缓冲数据
                builder.Clear();//清除字符串构造器的内容
                //因为要访问UI资源,所以需要使用invoke方式同步UI
                this.Invoke((EventHandler)(delegate
                {
                    //判断是否显示为16禁止
                    if (CheckBoxHexView.Checked)
                    {
                        //依次拼接出16进制字符串
                        foreach (byte b in buf)
                        {
                            builder.Append(b.ToString("X2") + "");
                        }
                    }
                    else
                    {
                        //直接按ASCII规则转换成字符串
                        builder.Append(Encoding.ASCII.GetString(buf));
                    }
                    //追加的形式添加到文本框尾端,并滚动到最后
                    this.txGet.AppendText(builder.ToString());
                    //修改接收计数
                    LabelGetCount.Text = "Get:" + received_count.ToString();
                }
                ));
            }
            finally
            {
                Listening = false;//我用完了,UI可以关闭串口了
            }
        }

        private void checkBoxNewlineGet_CheckedChanged(object sender, EventArgs e)
        {
            txGet.WordWrap = checkBoxNewlineGet.Checked;
        }
        //
        private void ButtonSend_Click(object sender, EventArgs e)
        {
            //定义一个变量,记录发送了几个字节
            int n = 0;
            //16进制发送
            if (CheckBoxHexSend.Checked)
            {
                //我们不管规则了。如果写错了一些,我们是允许的,只用正则得到的有效地十六进制数
                MatchCollection mc = Regex.Matches(txSend.Text, @"(?i[/da-f])");
                List<byte> buf = new List<byte>();//填充到这个临时列表中
                //依次添加到列表中
                foreach (Match m in mc)
                {
                    buf.Add(byte.Parse(m.Value));
                }
                //转换列表为数组后发送
                comn.Write(buf.ToArray(), 0, buf.Count);
                //记录发送的字节数
                n = buf.Count;
            }
            else
            {
                //包含换行符
                if (CheckBoxNewlineSend.Checked)
                {
                    comn.WriteLine(txSend.Text);
                    n = txSend.Text.Length + 2;
                }
                else
                {
                    comn.Write(txSend.Text);
                    n = txSend.Text.Length;
                }
            }
            send_count += n;//累加发送字节数
            LabelSendCount.Text = "Send:" + send_count.ToString();//更新界面
        }
        private void ButtonReset_Click(object sender, EventArgs e)
        {
            //复位接收和发送的字节数计数器并更新界面
            send_count = received_count = 0;
            LabelGetCount.Text = "Get:0";
            LabelSendCount.Text = "Send:0";
        }
        private void ButtonOpenClose_Click(object sender, EventArgs e)
        {
            //根据当前串口对象,来判断操作
            if (comn.IsOpen)
            {
                PortClosing = true;
                while (Listening)
                    Application.DoEvents();
                comn.Close();
                PortClosing = false;
            }
            else
            {
                //关闭点击时,则关闭串口
                comn.PortName = ComboBoxPortName.Text;
                comn.BaudRate = int.Parse(ComboBoxBaudrate.Text);
                try
                {
                    comn.Open();
                }
                catch (Exception ex)
                {
                    //捕获到异常信息,创建一个新的comn对象,之前的不能用了
                    comn = new SerialPort();
                    //显示异常
                    MessageBox.Show(ex.Message);
                }
            }
            //设置按钮的状态
            ButtonOpenClose.Text = comn.IsOpen ? "Close" : "Open";
            ButtonSend.Enabled = comn.IsOpen;
        }
    }

}


以下是使用C#编写串口调试助手的步骤: 1. 创建一个Windows窗口应用程序。 2. 在窗口中添加一个文本框和一个按钮,用于输入和发送串口数据。 3. 在窗口中添加一个下拉框,用于选择串口号和波特率。 4. 在代码中引用System.IO.Ports命名空间,以便使用串口通信相关的类。 5. 在代码中实例化SerialPort类,并设置串口号、波特率、数据位、停止位、校验位等参数。 6. 在代码编写串口数据发送和接收的相关函数,并将其与按钮单击事件关联。 7. 在代码编写串口数据接收的事件处理函数,并将其与SerialPort类的DataReceived事件关联。 8. 在代码中添加异常处理,以便在串口通信出现错误时进行处理。 下面是一个简单的C#串口调试助手代码示例: ```csharp using System; using System.IO.Ports; using System.Windows.Forms; namespace SerialPortDemo { public partial class Form1 : Form { private SerialPort serialPort; public Form1() { InitializeComponent(); serialPort = new SerialPort(); serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); } private void Form1_Load(object sender, EventArgs e) { string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } comboBox1.SelectedIndex = 0; comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (serialPort.IsOpen) { serialPort.Write(textBox1.Text); } } private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); this.Invoke(new Action(() => { textBox2.AppendText(indata); })); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { serialPort.PortName = comboBox1.SelectedItem.ToString(); } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { serialPort.BaudRate = int.Parse(comboBox2.SelectedItem.ToString()); } private void button2_Click(object sender, EventArgs e) { try { if (!serialPort.IsOpen) { serialPort.Open(); button2.Text = "关闭串口"; } else { serialPort.Close(); button2.Text = "打开串口"; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值