C# 自己写的串口助手,支持高波特率921600

一、界面:

主要代码如下:

(1)窗体加载

private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                cmbBTL.SelectedIndex = 6;
                cmbDataBit.SelectedIndex = 0;
                cmbJYBit.SelectedIndex = 0;
                cmbStopBit.SelectedIndex = 0;
                cmbDataType.SelectedIndex = 1;

                ckShowRecData.Checked = true;
                ckShowSendData.Checked = true;


                for (int i = 0; i < 7; i++)
                {
                    lstTs1[i] = new List<CANObj>();
                }

                debug_1_6[0] = "";
                debug_1_6[1] = "";
                debug_1_6[2] = "";
                debug_1_6[3] = "";
                debug_1_6[4] = "";
                debug_1_6[5] = "";
                debug_1_6[6] = "";

                Thread thRec = new Thread(ShowReciData);
                thRec.IsBackground = true;
                thRec.Start();

                Thread thSend = new Thread(ShowSendData);
                thSend.IsBackground = true;
                thSend.Start();

                //Thread thR = new Thread(DataReceived);
                //thR.IsBackground = true;
                //thR.Start();

                //Thread tBt = new Thread(SaveRecData);
                //tBt.IsBackground = true;
                //tBt.Start();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

(2)COM口加载:

private void cmbCOM_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                cmbCOM.Items.Clear();
                List<string> coms = new List<string>();
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
                {
                    var hardInfos = searcher.Get();
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties["Name"].Value != null)
                        {
                            if (hardInfo.Properties["Name"].Value.ToString().Contains("COM"))
                            {
                                coms.Add(hardInfo.Properties["Name"].Value.ToString());
                            }
                        }
                    }
                    searcher.Dispose();
                }

                string[] portNames = coms.ToArray();
                foreach (string portName in portNames)
                {
                    ShowSendInfo(portName + "\r\n");
                    if (portName.Contains("COM"))
                    {
                        string com = portName.Substring(portName.IndexOf('(') + 1, portName.IndexOf(')') - portName.IndexOf('(') - 1);
                        string[] scoms = com.Replace("->", " ").Split(' ');
                        if (scoms.Length == 2)
                        {
                            cmbCOM.Items.Add(scoms[0]);
                        }
                        else
                        {
                            cmbCOM.Items.Add(com);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

(3)打开串口:

SerialPort serialPort;
        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnOpen.Text == "打开串口")
                {
                    string portName = cmbCOM.Text;
                    int baudRate = int.Parse(cmbBTL.Text);
                    int dataBits = int.Parse(cmbDataBit.Text);
                    float stopBit = float.Parse(cmbStopBit.Text);
                    string parity = cmbJYBit.Text;
                    ConnectSerialPort("", portName, baudRate, dataBits, stopBit, parity, ref serialPort);
                    if (serialPort != null && serialPort.IsOpen)
                    {
                        btnOpen.Text = "关闭串口";
                        btnOpen.BackColor = Color.Green;
                        lbLampStats.BackColor = Color.Green;
                        serialPort.DataReceived += Sp1_DataReceived;
                    }
                }
                else
                {
                    btnOpen.Text = "打开串口";
                    btnOpen.BackColor = Color.White;
                    lbLampStats.BackColor = Color.LightGray;
                    if (serialPort != null)
                    {
                        serialPort.DataReceived -= Sp1_DataReceived;
                        serialPort.Dispose();
                    }
                    serialPort = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

(4)串口连接:

void ConnectSerialPort(string name, string portName, int baudRate, int dataBits, float stopBit, string parity, ref SerialPort sp)
        {
            try
            {

                sp = new SerialPort();
                sp.PortName = portName;
                sp.BaudRate = baudRate;
                sp.DataBits = dataBits;

                if (stopBit == 1)
                {
                    sp.StopBits = StopBits.One;
                }
                else if (stopBit == 1.5)
                {
                    sp.StopBits = StopBits.OnePointFive;
                }
                else if (stopBit == 2)
                {
                    sp.StopBits = StopBits.Two;
                }
                else
                {
                    sp.StopBits = StopBits.One;
                }

                if (parity.CompareTo("None") == 0)
                {
                    sp.Parity = Parity.None;
                }
                else if (parity.CompareTo("Odd") == 0)
                {
                    sp.Parity = Parity.Odd;
                }
                else if (parity.CompareTo("Even") == 0)
                {
                    sp.Parity = Parity.Even;
                }
                else
                {
                    sp.Parity = Parity.None;
                }

                sp.ReadTimeout = -1;     //  设置超时读取时间
                sp.RtsEnable = true;
                sp.ReceivedBytesThreshold = 1;

                if (!sp.IsOpen)
                {
                    sp.Open();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("串口设备,异常错误:" + ex.Message);
                sp = null;
            }
        }

(5)串口事件接收:

void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs arg)
        {
            try
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] receivedData = new byte[serialPort.BytesToRead];        //创建接收字节数组
                serialPort.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                if (receivedData.Length > 0)
                {
                    string strRec = "";
                    string dataType = "HEX";
                    cmbDataType.Invoke(new Action(() =>
                    {
                        dataType = cmbDataType.Text;
                    }));

                    if (dataType == "HEX")
                    {
                        for (int i = 0; i < receivedData.Length; i++) //窗体显示
                        {
                            strRec += receivedData[i].ToString("X2") + " ";  //16进制显示                            
                        }

                    }
                    else
                    {
                        strRec = asciiEncoding.GetString(receivedData);
                    }
                    reciveCount += receivedData.Length;

                    if (hcRecData.Count < 500000)
                    {
                        string hcData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff") + "->" + strRec;
                        hcRecData.Add(hcData);
                    }
                    else
                    {
                        string hcData = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff") + "->" + strRec;
                        hcRecData.RemoveAt(0);
                        hcRecData.Add(hcData);
                    }

                    //if (ckShowRecData.Checked)
                    //{
                    //    ShowSendInfo(strRec);
                    //}

                }
            }
            catch (Exception ex)
            {

            }
        }

结尾:代码太多,没有一一列出,感兴趣的伙伴可以到我上传的资源中下载源代码!!!

https://download.csdn.net/download/zd8766zd/89385317

Qt是一个跨平台的C++应用程序框架,它提供了一个强大的模块QSerialPort用于串口通信。设置串口波特率921600通常是在创建QSerialPort对象并配置其属性时完成的。以下是一个简单的步骤示例: ```cpp #include <QObject> #include <QSerialPort> class SerialPortHandler : public QObject { Q_OBJECT public: explicit SerialPortHandler(QObject *parent = nullptr) : QObject(parent) { // 创建QSerialPort实例 QSerialPort serial; // 设置端口号,这里假设是COM1,实际应用中替换为你需要的端口号 serial.setPortName(QStringLiteral("COM1")); // 设置波特率 serial.setBaudRate(QSerialPort::Baud9600); // 这里设置为921600,注意Qt使用的是近似值,可能需要进一步调整 if (!serial.open(QIODevice::ReadWrite)) { qCritical() << "Failed to open serial port."; return; } // 如果需要,可以添加其他配置如数据位、停止位和校验位等 // serial.setDataBits(QSerialPort::Data8); // serial.setParity(QSerialPort::NoParity); // serial.setStopBits(QSerialPort::OneStop); emit connected(); // 发出连接信号 } }; // 使用时,通过connect信号槽关联处理连接事件 void mainFunction() { SerialPortHandler handler; connect(&handler, &SerialPortHandler::connected, []() { qDebug() << "Connected to serial port at 921600 baud rate."; }); } ``` 在这个例子中,`setBaudRate()`函数设置了波特率921600,但Qt库内部可能会将其转换为最接近的可用速率,所以最好在实际操作前确认是否成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值