C# - [ 实践 ] 串口调试助手 v1.0

▶ 界面:

▶ 实现:

using System;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;

namespace SerialPort_Exp_1
{
    public partial class Form1 : Form
    {
        bool _port_is_open = false;
        SerialPort sp = null;
        public Form1()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //串口号预加载
            for (int i = 0; i < 10; i++)
            {
                serialport_cbx.Items.Add("COM" + (i + 1));
            }
            serialport_cbx.SelectedIndex = 0;
            //校验位预加载
            parity_cbx.Items.Add("无");
            parity_cbx.Items.Add("奇校验");
            parity_cbx.Items.Add("偶校验");
            parity_cbx.SelectedIndex = 0;
            //波特率预加载
            baudrate_cbx.Items.Add(1200);
            baudrate_cbx.Items.Add(3400);
            baudrate_cbx.Items.Add(4800);
            baudrate_cbx.Items.Add(9600);
            baudrate_cbx.Items.Add(19200);
            baudrate_cbx.Items.Add(38400);
            baudrate_cbx.Items.Add(43000);
            baudrate_cbx.Items.Add(56000);
            baudrate_cbx.Items.Add(57600);
            baudrate_cbx.Items.Add(115200);
            baudrate_cbx.SelectedIndex = 3;
            //数据位预加载
            databits_cbx.Items.Add(5);
            databits_cbx.Items.Add(6);
            databits_cbx.Items.Add(7);
            databits_cbx.Items.Add(8);
            databits_cbx.SelectedIndex = 2;
            //停止位预加载
            stopbits_cbx.Items.Add(0);
            stopbits_cbx.Items.Add(1);
            stopbits_cbx.Items.Add(1.5);
            stopbits_cbx.Items.Add(2);
            stopbits_cbx.SelectedIndex = 1;
        }

        ///检测可用端口
        private void check_port_button_Click(object sender, EventArgs e)
        {
            ///可用串口检测
            bool com_existence = false;
            //清除当前所有串口选项
            serialport_cbx.Items.Clear();
            for(int i = 0; i < 10; i++)
            {
                try
                {
                    var sp = new SerialPort("COM" + (i + 1));
                    sp.Open();
                    sp.Close();
                    serialport_cbx.Items.Add("COM" + (i + 1));
                    com_existence = true;
                }
                catch(Exception)
                {
                    continue;
                }
            }
            if (com_existence)
            {
                serialport_cbx.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未发现可用串口!", "错误提示");
            }
            
        }

        ///检测待发送的数据是否为空
        private bool checkSendData()
        {
            if (send_textbox.Text.Trim() == "") return false;
            return true;
        }

        ///检测串口参数是否全部配置(开启端口前测试)
        private bool checkPortSetting()
        {
            if (serialport_cbx.Text.Trim() == "") return false;
            if (parity_cbx.Text.Trim() == "") return false;
            if (baudrate_cbx.Text.Trim() == "") return false;
            if (databits_cbx.Text.Trim() == "") return false;
            if (stopbits_cbx.Text.Trim() == "") return false;
            return true;
        }

        ///端口开启
        private void open_port_button_Click(object sender, EventArgs e)
        {
            if (_port_is_open==false)
            {
                if (!checkPortSetting())
                {
                    MessageBox.Show("串口未正确配置!", "错误提示");
                    return;
                }
                try
                {
                    _port_is_open = true;
                    setPortProperty();    //转换窗口参数
                    sp.Open();
                    this.Invoke(new Action(() => { open_port_button.Text = "关闭端口"; }));
                    serialport_cbx.Enabled = false;
                    parity_cbx.Enabled = false;
                    baudrate_cbx.Enabled = false;
                    databits_cbx.Enabled = false;
                    stopbits_cbx.Enabled = false;
                    check_port_button.Enabled = false;
                }
                catch (Exception)
                {
                    _port_is_open = false;
                    MessageBox.Show("串口已被占用!", "错误提示");
                }
            }
            else
            {
                try
                {
                    _port_is_open = false;
                    sp.Close();
                    this.Invoke(new Action(() => { open_port_button.Text = "开启端口"; }));
                    serialport_cbx.Enabled = true;
                    parity_cbx.Enabled = true;
                    baudrate_cbx.Enabled = true;
                    databits_cbx.Enabled = true;
                    stopbits_cbx.Enabled = true;
                    check_port_button.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString(), "错误提示");
                }
            }
            //接收事件绑定
            sp.DataReceived += new SerialDataReceivedEventHandler(spDataReceived);
        }

        ///转换窗口串口属性
        private void setPortProperty()
        {
            sp = new SerialPort();
            sp.PortName = serialport_cbx.Text.Trim();
            sp.DataBits = Convert.ToInt32(databits_cbx.Text.Trim());
            sp.BaudRate = Convert.ToInt32(baudrate_cbx.Text.Trim());
            //转换停止位
            float stop_bits = Convert.ToSingle(stopbits_cbx.Text.Trim());
            if (stop_bits == 0)
            {
                sp.StopBits = StopBits.None;
            }
            else if(stop_bits == 1)
            {
                sp.StopBits = StopBits.One;
            }
            else if(stop_bits == 1.5)
            {
                sp.StopBits = StopBits.OnePointFive;
            }
            else if(stop_bits == 2)
            {
                sp.StopBits = StopBits.Two;
            }
            else
            {
                sp.StopBits = StopBits.One;
            }
            //转换奇偶校验位
            string parity = parity_cbx.Text.Trim();
            if (parity == "无")
            {
                sp.Parity = Parity.None;
            }
            else if(parity == "奇校验")
            {
                sp.Parity = Parity.Odd;
            }
            else
            {
                sp.Parity = Parity.Even;
            }
        }

        //数据接收事件(接收字符)
        private void spDataReceived(object sender,SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(200);
            this.Invoke(new Action(()=> {
                string rec_str = "";
                int bytes_count = sp.BytesToRead;
                byte[] byte_list = new byte[bytes_count];
                sp.Read(byte_list, 0, bytes_count);
                foreach (var i in byte_list)
                {
                    rec_str += (char)i;
                }
                receive_textbox.Text += rec_str;

                sp.DiscardInBuffer();    //丢弃接收缓冲区数据
            }));
        }

        private void send_button_Click(object sender, EventArgs e)
        {
            if (_port_is_open)
            {
                try
                {
                    sp.WriteLine(send_textbox.Text.Trim());
                }
                catch (Exception)
                {
                    MessageBox.Show("发送数据时出现错误!", "错误提示");
                }
            }
            else
            {
                MessageBox.Show("端口未开启!", "错误提示");
                return;
            }
            if (!checkSendData())
            {
                MessageBox.Show("发送数据不可为空!", "错误提示");
            }
            
        }

        private void clear_button_Click(object sender, EventArgs e)
        {
            send_textbox.Clear();
        }
    }
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值