C# development serial port assistant (can change the baud rate, serial port number, can realize the sending and receiving of data and characters)

0. Preface

1. Project realization

1.1 Configure Form1.cs[Design] file (Designer)

First, put the following Labelcontrols: ComboBox, RadioButton, Panel, Button, TextBox, ,GroupBox
Insert picture description here

In addition, you also need to add the SerialPort control.

1.1.1 The role of adding Panel

  • Panel is a container control. The official description of the role of Panel is: Allows grouping of control sets.
  • In the above figure, use Panel to divide the four RadioButtons into two groups. This can be achieved. In each group, only one RadioButton will be selected.
  • If the Panel is not used to group the four RadioButtons, one and only one of these four RadioButtons will be selected at the same time.

1.1.2 Add scroll bar to TextBox

The TextBox in these two places may have a large amount of data input or output. When the amount of data exceeds the visible range, a scroll bar is needed to expand the display range.
Insert picture description here
Click on one of the TextBoxes where you want to add a scroll bar, and then modify the ScrollBars in the property bar. Vertical is to add a vertical scroll bar, Horizontal is to add a horizontal scroll bar, and Both is to add both a vertical scroll bar and a horizontal scroll bar.
Insert picture description here

1.1.3 Configure comboBox_baud

Click the comboBox in the figure below.
Insert picture description here
Then modify the Items option in its property bar:
Insert picture description here

Pre-fill the baud rate in the set.

Insert picture description here

1.1.4 Special circumstances

If you add a control but forget the name of the control, you can click on the control and get it from the name in the control property bar.
Insert picture description here

Insert picture description here

1.2 Configure the Form1.cs file

The code of Form1.cs is as follows

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;
using System.IO.Ports;  //这个引用一定要加上

namespace SerialCommunicate
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            for (int i = 1; i < 20; i++)
            {
    
    
                comboBox_port.Items.Add("COM" + i.ToString()); //从1至19添加串口号
            }
            comboBox_port.Text = "COM1";//串口号多额默认值
            comboBox_baud.Text = "9600";//波特率默认值(其他波特率在属性的Items内添加)

            /*****************非常重要************************/

            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);//必须手动添加事件处理程序(接收串口数据)
        }

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)//串口数据接收事件
        {
    
    
            if (!radioButton_rxd_int.Checked)//如果接收模式为字符模式
            {
    
    
                string str = serialPort1.ReadExisting();//字符串方式读
                textBox_rxd.AppendText(str);//添加内容
            }
            else
            {
    
     //如果接收模式为数值接收
                byte data;
                data = (byte)serialPort1.ReadByte();//此处需要强制类型转换,将(int)类型数据转换为(byte类型数据,不必考虑是否会丢失数据
                string str = Convert.ToString(data, 16).ToUpper();//转换为大写十六进制字符串
                textBox_rxd.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//空位补“0”   
                //上一句等同为:if(str.Length == 1)
                //                  str = "0" + str;
                //              else 
                //                  str = str;
                //              textBox_rxd.AppendText("0x" + str);
            }
        }
        private void button_open_port_Click(object sender, EventArgs e)
        {
    
    
            try
            {
    
    
                serialPort1.PortName = comboBox_port.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox_baud.Text, 10);//十进制数据转换(波特率是字符型的,需要转换为十进制整形)
                serialPort1.Open();
                button_open_port.Enabled = false;//打开串口按钮不可用(“打开串口”按钮在刚打开软件时应该是可用的,需要将设计器内button_open_port属性中的Enabled设置为True)
                button_close_port.Enabled = true;//关闭串口(“关闭串口”按钮在刚打开软件时应该是不可用的,需要将设计器内button_close_port属性中的Enabled设置为False)
            }
            catch
            {
    
    
                MessageBox.Show("端口错误,请检查串口", "错误");
            }
        }

        private void button_close_port_Click(object sender, EventArgs e)
        {
    
    
            try
            {
    
    
                serialPort1.Close();//关闭串口
                button_open_port.Enabled = true;//打开串口按钮可用
                button_close_port.Enabled = false;//关闭串口按钮不可用
            }
            catch (Exception err)//一般情况下关闭串口不会出错,所以不需要加处理程序
            {
    
    

            }
        }

        private void button_empty_output_Click(object sender, EventArgs e)
        {
    
    
            textBox_rxd.Text = "";
        }

        private void button_launch_Click(object sender, EventArgs e)
        {
    
    
            byte[] Data = new byte[1];//作用同上集
            if (serialPort1.IsOpen)//判断串口是否打开,如果打开执行下一步操作
            {
    
    
                if (textBox_txd.Text != "")
                {
    
    
                    if (!radioButton_txd_int.Checked)//如果发送模式是字符模式
                    {
    
    
                        try
                        {
    
    
                            serialPort1.WriteLine(textBox_txd.Text);//写数据
                        }
                        catch (Exception err)
                        {
    
    
                            MessageBox.Show("串口数据写入错误", "错误");//出错提示
                            serialPort1.Close();
                            button_open_port.Enabled = true;//打开串口按钮可用
                            button_close_port.Enabled = false;//关闭串口按钮不可用
                        }
                    }
                    else
                    {
    
    
                        for (int i = 0; i < (textBox_txd.Text.Length - textBox_txd.Text.Length % 2) / 2; i++)//取余3运算作用是防止用户输入的字符为奇数个
                        {
    
    
                            Data[0] = Convert.ToByte(textBox_txd.Text.Substring(i * 2, 2), 16);
                            serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
                        }
                        if (textBox_txd.Text.Length % 2 != 0)//剩下一位单独处理
                        {
    
    
                            Data[0] = Convert.ToByte(textBox_txd.Text.Substring(textBox_txd.Text.Length - 1, 1), 16);//单独发送B(0B)
                            serialPort1.Write(Data, 0, 1);//发送
                        }
                    }
                }
            }
        }

//下面这个事件是"串口自动检测"按钮按下后将会触发的时间。
//因为在本文中,代码更新了但是上位机的图片没更新。
//所以如果想要增加此功能的话,请自行在设计器中增加一个名为"button_auto_detect"的按钮控件。
        private void button_auto_detect_Click(object sender, EventArgs e)
        {
    
    
            bool comExistence = false; //有可用的串口标志位
            comboBox_port.Items.Clear(); //清除当前串口号中所有串口名称
            for (int i = 0; i < 19; i++)
            {
    
    
                try
                {
    
    
                    SerialPort sp = new SerialPort("COM" + (i + 1).ToString()); //串口实例化
                    sp.ReadBufferSize = 1024000; //设置接收缓存
                    sp.Open();
                    sp.Close();
                    comboBox_port.Items.Add("COM" + (i + 1).ToString());
                    comExistence = true;
                }
                catch (Exception)
                {
    
    
                    continue;
                }
                if (comExistence)
                {
    
    
                    comboBox_port.SelectedIndex = 0; //使ListBox显示第1个添加的索引
                    break; //找到一个可用的串口即可
                }
                else
                {
    
    
                    MessageBox.Show("没有找到可用串口!", "错误提示"); //显示具有指定文本和标题的消息框
                }
            }
        }
    }
}

2. Serial port assistant preview

Insert picture description here

3. Test

3.1 Configure virtual serial port pair

Open VSPD, configure a serial port pair of COM3 and COM4, ​​and then click Add pair.
Insert picture description here
Get a virtual serial port pair: COM3 and COM4.
Insert picture description here
You can also view the virtual serial port pair in the device manager.
Insert picture description here

3.2 Configure SSCOM

Open SSCOM. Configure the serial port number as COM4 and the baud rate to 9600.

Insert picture description here

3.3 Configure serial port assistant

Open the serial port assistant, configure the serial port number as COM3, the baud rate is 9600, and change the sending and receiving mode to character (change the sending and receiving mode to character mode only for more intuitive display, and the numerical mode can also work normally) .
Insert picture description here

3.4 Start experiment

Click to open the serial port in SSCOM.
Insert picture description here
Click to open the port in the serial port assistant.
Insert picture description here
Enter 555 in the input box of the serial port assistant, and 555 can be received in the receiving box of SSCOM.
Insert picture description here

Enter 666 in the input box of SSCOM, and you can receive 666 in the receiving box of the serial port assistant.
Insert picture description here

Guess you like

Origin blog.csdn.net/mahoon411/article/details/109346704
Recommended