一路向北lm 发表于 2019-5-15 12:27

开源一个Qt串口助手,自己编写,请大佬们指点。

本帖最后由 一路向北lm 于 2019-5-15 12:37 编辑

界面如下图所示:

工程源码打包:

一路向北lm 发表于 2019-5-15 12:29

mainwindow.cpp 文件
#include "mainwindow.h"
#include "ui_mainwindow.h"


unsigned char i =0;    //串口打开标志重绘图像变量

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("串口调试助手V1.0");
    Serial_Port_Init();//串口初始化
   // QwtPlot_Init();      //QwtPlot初始化
    //InitTimer0();      //定时器初始化
}

MainWindow::~MainWindow()
{
    delete ui;
}


// 串口初始化函数
void MainWindow::Serial_Port_Init()
{
    connect(&serial,SIGNAL(readyRead()),this,SLOT(serialRead())); //连接槽
    //获取计算机上所有串口并添加到comboBox中
    QList<QSerialPortInfo>infos = QSerialPortInfo::availablePorts();
    if(infos.isEmpty())
   {
      ui->comboBox->addItem("无串口");
      return;
   }
   foreach (QSerialPortInfo info, infos)
   {
         ui->comboBox->addItem(info.portName());
         qDebug() << info.portName();
   }

   // 为波特率下拉框添加数据
   QStringList baund_strList;
   baund_strList<<"300"<<"1200"<<"2400"<<"4800"<<"9600"<<"19200"<<"38400"<<"56000"<<"57600"<<"115200"<<"128000";
   ui->ComBox_BaudRate->addItems(baund_strList);
   ui->ComBox_BaudRate->setCurrentText("9600");
   // 为数据位下拉框添加数据
   QStringList Data_strList;
   Data_strList<<"5"<<"6"<<"7"<<"8";
   ui->ComBox_DataBits->addItems(Data_strList);
   ui->ComBox_DataBits->setCurrentText("8");
   // 为校验位下拉框添加数据
   QStringList Check_strList;
   Check_strList<<"None"<<"Odd"<<"Even"<<"Mark"<<"Space";
   ui->ComBox_CheckBits->addItems(Check_strList);
   ui->ComBox_CheckBits->setCurrentText("None");
    // 为停止位下拉框添加数据
   QStringList Stop_strList;
   Stop_strList<<"1"<<"2";
   ui->ComBox_StopBits->addItems(Stop_strList);
   ui->ComBox_StopBits->setCurrentText("1");

   // 控件颜色初始化
   ui->textBrowser->setStyleSheet("color:white;background:black;");
   ui->textEdit->setStyleSheet("color:white;background:black;");

   //第一个属性是字体(微软雅黑),第二个是大小,第三个是加粗(权重是75)
   //常见权重
   //QFont::Light - 25 高亮
   //QFont::Normal - 50 正常
   //QFont::DemiBold - 63 半粗体
   //QFont::Bold - 75 粗体
   //QFont::Black - 87 黑体
   QFont font1("Microsoft YaHei",11,50);
   ui->label_port->setFont(font1);
   ui->label_baund->setFont(font1);
   ui->label_data->setFont(font1);
   ui->label_check->setFont(font1);
   ui->label_stop->setFont(font1);


   QFont font2("Microsoft YaHei",10,50);
   ui->comboBox->setFont(font2);
   ui->ComBox_BaudRate->setFont(font2);
   ui->ComBox_DataBits->setFont(font2);
   ui->ComBox_CheckBits->setFont(font2);
   ui->ComBox_StopBits->setFont(font2);
   ui->open_serial_Button->setFont(font2);
   ui->Clear_RC_Button->setFont(font2);
   ui->Clear_Send_Button->setFont(font2);
   ui->Send_Button->setFont(font2);
}
// 串口打开按钮处理函数
void MainWindow::on_open_serial_Button_clicked()
{
   if(ui->comboBox->isEnabled()) // 串口端口下拉框已使能
   {
      serial.setPortName(ui->comboBox->currentText()); //设置COM口
      serial.setBaudRate(ui->ComBox_BaudRate->currentText().toInt()); //设置波特率
      //设置数据位
      switch(ui->ComBox_DataBits->currentText().toInt())
      {
       case 5: serial.setDataBits(QSerialPort::Data5);break;
       case 6: serial.setDataBits(QSerialPort::Data6);break;
       case 7: serial.setDataBits(QSerialPort::Data7);break;
       case 8: serial.setDataBits(QSerialPort::Data8);break;
       default :                                        break;
      }
       //设置校验位
      if(ui->ComBox_CheckBits->currentText() == "None")
      {
          serial.setParity(QSerialPort::NoParity);
      }
      else if(ui->ComBox_CheckBits->currentText() == "Odd")
      {
         serial.setParity(QSerialPort::OddParity);
      }
      else if(ui->ComBox_CheckBits->currentText() == "Even")
      {
         serial.setParity(QSerialPort::EvenParity);
      }
      else if(ui->ComBox_CheckBits->currentText() == "Mark")
      {
         serial.setParity(QSerialPort::MarkParity);
      }
      else if(ui->ComBox_CheckBits->currentText() == "Space")
      {
         serial.setParity(QSerialPort::SpaceParity);
      }
      //设置停止位
      if(ui->ComBox_StopBits->currentText() == "1")
      {
          serial.setStopBits(QSerialPort::OneStop);
      }
      else if(ui->ComBox_StopBits->currentText() == "2")
      {
         serial.setStopBits(QSerialPort::TwoStop);
      }
      //设置硬件流控制:无控制
      serial.setFlowControl(QSerialPort::NoFlowControl);

      serial.close(); //先关串口,再打开,可以保证串口不被其它函数占用。
      if(serial.open(QIODevice::ReadWrite)) //以读写的方式打开串口
      {
         ui->open_serial_Button->setText("关闭串口"); //按下打开串口后,显示为关闭串口
         ui->comboBox->setDisabled(true);            //端口选择下拉框被禁止
         ui->ComBox_BaudRate->setDisabled(true);   //波特率选择下拉框被禁止
         ui->ComBox_DataBits->setDisabled(true);   //数据位选择下拉框被禁止
         ui->ComBox_CheckBits->setDisabled(true);    //校验位选择下拉框被禁止
         ui->ComBox_StopBits->setDisabled(true);   //停止位选择下拉框被禁止
         connect(&serial,SIGNAL(readyRead()),this,SLOT(Serial_Read()));        //把串口的readyRead()信号绑定到serialRead()这个槽函数上

         i=1;   //重绘串口打开标志图像
         update();
      }
      else ///串口打开失败
      {
          qDebug("串口已经被占用");
          QMessageBox::information(NULL, "错误", "串口已经被占用", QMessageBox::Yes | QMessageBox::No);


      }
   }
   else // 串口端口下拉框被禁用
   {
      ui->open_serial_Button->setText("打开串口"); //按下“关闭串口”后,按键显示为“打开串口”
      ui->comboBox->setEnabled(true);                     //按下“关闭串口”后,COM口可被修改
      ui->ComBox_BaudRate->setEnabled(true);   //波特率选择下拉框可被修改
      ui->ComBox_DataBits->setEnabled(true);   //数据位选择下拉框可被修改
      ui->ComBox_CheckBits->setEnabled(true);    //校验位选择下拉框可被修改
      ui->ComBox_StopBits->setEnabled(true);   //停止位选择下拉框可被修改
      serial.close();                                                   //关串口
      i = 0;         //重绘串口打开标志图像
      update();
   }
}

// 串口读取数据函数
void MainWindow:: Serial_Read()
{
    QByteArray buf;
    buf = serial.readAll();
    if(!buf.isEmpty())//如果读到的数据不为空
    {
       ui->textBrowser->insertPlainText(buf);
   }
   buf.clear();
}

// 串口发送数据函数
void MainWindow::on_Send_Button_clicked()
{
    serial.write(ui->textEdit->toPlainText().toLatin1()); //以ASC码形式发送
    serial.write("\r\n");
}

void MainWindow::paintEvent(QPaintEvent *)
{

    QPainter painter(this);
    if(i ==0)
    {
       painter.setPen(QPen(Qt::gray,4));//设置画笔形式
       painter.drawEllipse(25,206,20,20);//画圆
    }
    if(i==1)
    {
      painter.setBrush(QBrush(Qt::red));
      painter.drawEllipse(25,206,20,20);//画圆
    }

}




//// QwtPlot初始化函数
//// 初始化 标题title
//// 初始化 yLeft yRight xBottom xTop 及其titile
//void MainWindow::QwtPlot_Init()
//{


////    QwtText t;

////    t.setColor(QColor(255,0,0));
////    QBrush brush(QColor(0,0,255));
////    ui->qwtPlot->setTitle("温度曲线函数图像");

//    QwtText t;

//    t.setText("温度曲线函数图像"); //设置标题名
////    QFont font;//设置字体
////    font.setBold(true); //设置粗体
////    t.setFont(font);
//    t.setColor(QColor(255,0,0));//设置颜色
////    //设置标题背景色
////    QBrush brush(QColor(255,255,255));
////    t.setBackgroundBrush(brush);
//   ui->qwtPlot->setTitle(t);

////   ui->qwtPlot->setAxisScale(QwtPlot::yLeft,0,100,10);
////   ui->qwtPlot->setAxisScale(QwtPlot::xBottom,0,100,10);
////   ui->qwtPlot->setAxisTitle(QwtPlot::yLeft,"温度C");
////   ui->qwtPlot->setAxisTitle(QwtPlot::xBottom,"时间t/s");
//   //ui->qwtPlot->setAxisScale(QwtPlot::yRight,0,100,10);
//   //ui->qwtPlot->setAxisScale(QwtPlot::xTop,0,100,10);
//   //ui->qwtPlot->setAxisTitle(QwtPlot::xTop,QObject::trUtf8("Top"));
//   //ui->qwtPlot->setAxisTitle(QwtPlot::yRight,QObject::trUtf8("Right"));

//   //QwtPlot 绘制曲线图像(静态)
//   QwtPlotCurve *curve;
//   double time[]={1,2,3,4,5,6,7,8,9,10};
//   double val={0,0,1.5,2.6,3.8,5.7,5.9,4.2,3.5,0};
//   curve = new QwtPlotCurve("Acc_X");
//   curve->setSamples(time,val,10);
//   curve->attach(ui->qwtPlot);
//    // QwtPlot 绘制曲线图像(动态)




////   //数据x,y值保存
////   QVector<QPointF> vector;
////   for(int i =0;i<100;i++)
////   {
////         QPointF point;
////         point.setX(i);
////         int y = 20*sin(i*M_PI/10) + 50;
////         point.setY(y);
////         vector.append(point);
////   }
////   //构造曲线数据
////   QwtPointSeriesData* series = new QwtPointSeriesData(vector);

////   //create plot item
////   QwtPlotCurve* curve1 = new QwtPlotCurve("Curve 1");
////   curve1->setData(series);      //设置数据
////   curve1->attach(ui->qwtPlot); //把曲线附加到qwtPlot上

////   ui->qwtPlot->replot();
////   ui->qwtPlot->show();


//}

//void MainWindow::on_qwtPlot_legendDataChanged(const QVariant &itemInfo, const QList<QwtLegendData> &data)
//{

//}

//// 定时器初始化函数
//void MainWindow:: InitTimer0()
//{
//    timer0->start(2000);//启动或重启定时器, 并设置定时器时间:毫秒
//    connect(timer0, SIGNAL(timeout()), this, SLOT(Timer0TimeOut()));
//}

//// 定时器溢出处理函数
//void MainWindow::Timer0TimeOut()
//{

//}

// 清除接收数据单选按钮处理函数

void MainWindow::on_Clear_RC_Button_clicked()
{
       ui->textBrowser->clear();
}

void MainWindow::on_Clear_Send_Button_clicked()
{
    ui->textEdit->clear();
}


一路向北lm 发表于 2019-5-15 12:30

mainwindow.h 文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>
//#include <QTimer>
#include <QPainter>
#include <QMessageBox>


// qwt 第三方组件
//#include <qwt_plot.h>
//#include <qwt_plot_curve.h>









//串口头文件
#include <QSerialPort>      //提供访问串口的功能
#include <QSerialPortInfo>//提供系统中存在的串口的信息


namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

/************************串口部分*********************/
public:
QSerialPort serial;       //串口实例
void Serial_Port_Init();//初始化串口函数
private slots:
void on_open_serial_Button_clicked(); //串口打开按钮处理函数
void Serial_Read();                  //串口读取数据函数
void on_Send_Button_clicked();
/*****************************************************/
/************************QPainter部分*****************/


void on_Clear_RC_Button_clicked();
void on_Clear_Send_Button_clicked();

private:
    void paintEvent(QPaintEvent *); //画图函数

/*****************************************************/





/************************QwtPlot部分******************/
// void QwtPlot_Init();      //QwtPlot初始化
// void on_qwtPlot_legendDataChanged(const QVariant &itemInfo, const QList<QwtLegendData> &data);
/*****************************************************/


/************************定时器部分*********************/
//private:
//    QTimer *timer0;
//    void InitTimer0();
//private slots:
//    void Timer0TimeOut();


/*****************************************************/

};


#endif // MAINWINDOW_H


一路向北lm 发表于 2019-5-15 12:36

serial.pro文件
#-------------------------------------------------
#
# Project created by QtCreator 2019-05-11T17:20:42
#
#-------------------------------------------------

QT       += core gui

QT       += serialport   #添加串口
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = serial
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS


# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += main.cpp\
      mainwindow.cpp

HEADERS+= mainwindow.h

FORMS    += mainwindow.ui



#Qwt设置
DEFINES += QT_DLL QWT_DLL
LIBS += -L"D:\QT\5.8\mingw53_32\lib" -lqwtd      #qwtd.a 库路径
LIBS += -L"D:\QT\5.8\mingw53_32\lib" -lqwt       #qwt.a 库路径
INCLUDEPATH += D:\QT\5.8\mingw53_32\include\qwt#qwtd 头文件路径
#end qwt








xyz549040622 发表于 2019-5-15 12:42

支持下!

whtwhtw 发表于 2019-5-15 15:04

支持一下

一路向北lm 发表于 2019-5-15 20:01

xyz549040622 发表于 2019-5-15 12:42
支持下!

谢谢{:biggrin:}

一路向北lm 发表于 2019-5-15 20:01

whtwhtw 发表于 2019-5-15 15:04
支持一下

谢谢啦

yklstudent 发表于 2019-5-16 07:08

支持一下

fzy_666 发表于 2019-5-16 12:05

历害

一路向北lm 发表于 2019-5-16 14:59

fzy_666 发表于 2019-5-16 12:05
历害

哈哈,一般般

lxa0 发表于 2019-5-17 19:59

试用了,还不错!

一路向北lm 发表于 2019-5-18 12:23

lxa0 发表于 2019-5-17 19:59
试用了,还不错!

一般般 拿来练手的

enderman1 发表于 2019-5-20 12:37

哇,好棒棒~

一路向北lm 发表于 2019-5-21 12:36

enderman1 发表于 2019-5-20 12:37
哇,好棒棒~

一般吧,哈哈哈,谦虚

lihui567 发表于 2019-5-27 11:36

QT开发的话,用C++的较多,用c的话是不是也可以啊,老兄

一路向北lm 发表于 2019-5-27 21:14

lihui567 发表于 2019-5-27 11:36
QT开发的话,用C++的较多,用c的话是不是也可以啊,老兄

一般是C++ 你非要用C也可以

莫家良 发表于 2019-6-2 14:15

学习学习谢谢

一路向北lm 发表于 2019-6-2 19:44

莫家良 发表于 2019-6-2 14:15
学习学习谢谢

不用客气

奋斗小范 发表于 2019-6-8 13:27

看一下~~~
页: [1] 2
查看完整版本: 开源一个Qt串口助手,自己编写,请大佬们指点。