用QT写UART串口曲线变化

做项目经常会调试一下有变化规律的器件,如果只是打印出来显得观察变化规律不明显,所以自己用QT写了个串口数据变化曲线。

 

效果图:(点击查看,将就)

用QT写UART串口曲线变化_第1张图片

使用方法:

串口数据格式 (ASCII): 序号+空格+数据+空格。。。(后面数据不讲究)

                            如数据:642  22.4600  \r\n

序号为1的时候会重画另一条颜色不同的曲线。

 

缺点:不支持界面缩放(一开始没布局,差不多完成的时候才发现,屏幕分辩率1920*1080)

 

 

源码下载地址:https://download.csdn.net/download/sudaroot/11149854

源码:(因为程序用了一个第三方的qcustomplot库,下面我就不复制上来了,太大了,网上下载添加编译即可)

main.cpp

#include "mainwindow.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    w.setWindowTitle("Serial Port Curve Debugging");
    w.show();

    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 


static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A");


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    serial(new QSerialPort)
{
    ui->setupUi(this);

    curveZoom_flag = 1;

    fillPortsParameters();
    fillPortsInfo();
    SerialSetinfo();

    connect(ui->refreshButton, &QPushButton::clicked, this, &MainWindow::fillPortsInfo);    //按键刷新串口
    connect(ui->serialCtrlButton, &QPushButton::clicked, this, &MainWindow::switchSerialPort);  //串口开关
    connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
    connect(serial, &QSerialPort::errorOccurred, this, &MainWindow::handleError);
    connect(ui->clearDataButton, &QPushButton::clicked, this, &MainWindow::clearData);
    connect(ui->sendDataButton, &QPushButton::clicked, this, &MainWindow::writeData);
    connect(ui->curveZoomButton, &QPushButton::clicked, this, &MainWindow::curveZoom);
    connect(ui->curveClearButton, &QPushButton::clicked, this, &MainWindow::curveClear);
    connect(ui->allClearButton, &QPushButton::clicked, this, &MainWindow::allClear);

    ui->curveShowWidget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom|
                                         QCP :: iSelectPlottables|QCP::iSelectItems|
                                         QCP :: iSelectAxes| QCP::iSelectLegend);
}

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

void MainWindow::fillPortsParameters()
{
    ui->baudRateBox->addItem(QStringLiteral("9600"), QSerialPort::Baud9600);
    ui->baudRateBox->addItem(QStringLiteral("19200"), QSerialPort::Baud19200);
    ui->baudRateBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400);
    ui->baudRateBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200);
    ui->baudRateBox->addItem(tr("Custom"));

    ui->dataBitsBox->addItem(QStringLiteral("5"), QSerialPort::Data5);
    ui->dataBitsBox->addItem(QStringLiteral("6"), QSerialPort::Data6);
    ui->dataBitsBox->addItem(QStringLiteral("7"), QSerialPort::Data7);
    ui->dataBitsBox->addItem(QStringLiteral("8"), QSerialPort::Data8);
    ui->dataBitsBox->setCurrentIndex(3);

    ui->parityBox->addItem(tr("None"), QSerialPort::NoParity);
    ui->parityBox->addItem(tr("Even"), QSerialPort::EvenParity);
    ui->parityBox->addItem(tr("Odd"), QSerialPort::OddParity);
    ui->parityBox->addItem(tr("Mark"), QSerialPort::MarkParity);
    ui->parityBox->addItem(tr("Space"), QSerialPort::SpaceParity);

    ui->stopBitsBox->addItem(QStringLiteral("1"), QSerialPort::OneStop);
    ui->stopBitsBox->addItem(QStringLiteral("2"), QSerialPort::TwoStop);

    ui->flowControlBox->addItem(tr("None"), QSerialPort::NoFlowControl);
    ui->flowControlBox->addItem(tr("RTS/CTS"), QSerialPort::HardwareControl);
    ui->flowControlBox->addItem(tr("XON/XOFF"), QSerialPort::SoftwareControl);
}

void MainWindow::fillPortsInfo()
{
    QString description, manufacturer, serialNumber;

    ui->serialPortInfoListBox->clear();
    const auto infos = QSerialPortInfo::availablePorts();
    for(const QSerialPortInfo &info : infos)
    {
        QStringList list;
        description = info.description();
        manufacturer = info.manufacturer();
        serialNumber = info.serialNumber();
        list << info.portName()
             << (!description.isEmpty() ? description : blankString)
             << (!manufacturer.isEmpty() ? manufacturer : blankString)
             << (!serialNumber.isEmpty() ? serialNumber : blankString)
             << info.systemLocation()
             << (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : blankString)
             <<(info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : blankString);

        ui->serialPortInfoListBox->addItem(list.first(), list.size());
    }
    ui->serialPortInfoListBox->addItem(tr("Custom"));
}

void MainWindow::SerialSetinfo()
{
    //串口名
    currentSerialSetings.name = ui->serialPortInfoListBox->currentText();

    //波特率
    if(ui->baudRateBox->currentIndex() == 4){
        currentSerialSetings.baudRate = ui->baudRateBox->currentText().toInt();
    }
    else{
        currentSerialSetings.baudRate = static_cast(ui->baudRateBox->itemData(ui->baudRateBox->currentIndex()).toInt());
    }
    currentSerialSetings.stringBaudRate = QString::number(currentSerialSetings.baudRate);

    //数据位
    currentSerialSetings.dataBits = static_cast(ui->dataBitsBox->itemData(ui->dataBitsBox->currentIndex()).toInt());
    currentSerialSetings.stringDataBits = ui->dataBitsBox->currentText();

    //校验位
    currentSerialSetings.parity = static_cast(ui->parityBox->itemData(ui->parityBox->currentIndex()).toInt());
    currentSerialSetings.stringParity = ui->parityBox->currentText();

    //停止位
    currentSerialSetings.stopBits = static_cast(ui->stopBitsBox->itemData(ui->stopBitsBox->currentIndex()).toInt());
    currentSerialSetings.stringStopBits = ui->stopBitsBox->currentText();

    //流控
    currentSerialSetings.flowControl = static_cast(ui->flowControlBox->itemData(ui->flowControlBox->currentIndex()).toInt());
    currentSerialSetings.stringFlowControl = ui->flowControlBox->currentText();
}

void MainWindow::openSerialPort()
{
    serial->setPortName(currentSerialSetings.name);
    serial->setBaudRate(currentSerialSetings.baudRate);
    serial->setDataBits(currentSerialSetings.dataBits);
    serial->setStopBits(currentSerialSetings.stopBits);
    serial->setParity(currentSerialSetings.parity);
    serial->setFlowControl(currentSerialSetings.flowControl);

    if(serial->open(QIODevice::ReadWrite)){
        qDebug() << "OK";
        ui->refreshButton->setEnabled(false);
        ui->serialPortInfoListBox->setEnabled(false);
        ui->baudRateBox->setEnabled(false);
        ui->dataBitsBox->setEnabled(false);
        ui->parityBox->setEnabled(false);
        ui->stopBitsBox->setEnabled(false);
        ui->flowControlBox->setEnabled(false);
        ui->serialCtrlButton->setText("关闭串口");
    }
    else {
        qDebug() << "ERROR";
        QMessageBox::critical(this, tr("Error"), serial->errorString());
    }
}

void MainWindow::closeSerialPort()
{
    if (serial->isOpen())
        serial->close();
    ui->refreshButton->setEnabled(true);
    ui->serialPortInfoListBox->setEnabled(true);
    ui->baudRateBox->setEnabled(true);
    ui->dataBitsBox->setEnabled(true);
    ui->parityBox->setEnabled(true);
    ui->stopBitsBox->setEnabled(true);
    ui->flowControlBox->setEnabled(true);
    ui->serialCtrlButton->setText("打开串口");
}

void MainWindow::switchSerialPort()
{
    SerialSetinfo();
    if(serial_flag == 0){
        serial_flag = 1;
        openSerialPort();
    }
    else {
        serial_flag = 0;
        closeSerialPort();
    }
}

void MainWindow::readData()
{
    static int graph_count = 0;
    static unsigned long count = 0;
    QColor test[12] = {
        Qt:: black, Qt:: red, Qt:: green, Qt:: blue, Qt:: cyan,
        Qt:: magenta, Qt:: darkRed, Qt:: darkGreen,
        Qt:: darkBlue, Qt:: darkCyan, Qt:: darkMagenta, Qt:: darkYellow
    };

    QByteArray temp = serial->readAll();

    if(temp.isEmpty() != true){
#if 1
        QString str = ui->receiveDataText->toPlainText();  //添加文本
        str+=tr(temp);
        ui->receiveDataText->clear();
        ui->receiveDataText->append(str);
#else
        ui->receiveDataText->append(temp);  //添加文本
#endif
        QByteArrayList list = temp.split(' '); //分割字符串

        if(list.count() < 2)                //数据缺失,丢包
            return;

        unsigned int num = list[0].toUInt();
        double  r_data = list[1].toDouble();

        graph_count = ui->curveShowWidget->graphCount();
        if(num == 1 || graph_count == 0 )
        {
            ui->curveShowWidget->addGraph();
            graph_count = ui->curveShowWidget->graphCount();
            qDebug() << graph_count;
            ui->curveShowWidget->graph(graph_count - 1)->setPen(QPen(test[graph_count % 12 - 1]));
            count = 0;
        }

        ui->curveShowWidget->graph(graph_count - 1)->addData(count++, r_data);
        if(curveZoom_flag == 1){
            ui->curveShowWidget->graph(graph_count - 1)->rescaleKeyAxis(true);
            ui->curveShowWidget->graph(graph_count - 1)->rescaleValueAxis(true);
            ui->curveShowWidget->graph(graph_count - 1)->rescaleAxes(true);
        }
        ui->curveShowWidget->replot();
    }
}

void MainWindow::clearData()
{
    ui->receiveDataText->clear();
}

void MainWindow::writeData()
{
    if(ui->sendDataText->toPlainText().isEmpty() != true){
        serial->write(ui->sendDataText->toPlainText().toLatin1());
    }
}


void MainWindow::curveZoom()
{
    if(curveZoom_flag == 0){
        ui->curveZoomButton->setText("关闭缩放");
        curveZoom_flag = 1;
    }
    else {
        ui->curveZoomButton->setText("自动缩放");
        curveZoom_flag = 0;
    }
}

void MainWindow::curveClear()
{
    int i = 0;
    int graph_count = ui->curveShowWidget->graphCount();

    for(i = 0; i < graph_count; i++)
    {
        ui->curveShowWidget->removeGraph(i);
    }
}

void MainWindow::allClear()
{
    curveClear();
    clearData();
}


void MainWindow::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        closeSerialPort();
    }
}

 mainwindow.ui



 MainWindow
 
  
   
    0
    0
    1920
    1000
   
  
  
   MainWindow
  
  
   
    
     
      0
      970
      101
      20
     
    
    
     Author:sudaroot
    
   
   
    
     
      159
      39
      1461
      921
     
    
   
   
    
     
      20
      40
      124
      921
     
    
    
     
      
       
        
         宋体
         14
        
       
       
        串口设置:
       
       
        Qt::AlignCenter
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         端  口
        
       
       
        
         -1
        
        
         -1
        
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         17
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         波特率
        
       
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         数据位
        
       
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         17
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         校验位
        
       
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         停止位
        
       
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
     
      
       
        Qt::Horizontal
       
       
        
         
          宋体
          12
         
        
        
         流  控
        
       
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         105
         50
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        刷新
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         30
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        打开串口
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         80
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        曲线设置:
       
       
        Qt::AlignCenter
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         115
         13
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        关闭缩放
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        清除曲线
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         20
         100
        
       
      
     
     
      
       
        
         宋体
         12
        
       
       
        全部清除
       
      
     
     
      
       
        Qt::Vertical
       
       
        
         122
         13
        
       
      
     
    
   
   
    
     
      830
      12
      111
      24
     
    
    
     
      宋体
      18
     
    
    
     曲线显示
    
    
     Qt::AlignCenter
    
   
   
    
     
      1630
      32
      263
      610
     
    
    
     
      
       
        
         
          Qt::Horizontal
         
         
          
           78
           20
          
         
        
       
       
        
         
          
           宋体
           14
          
         
         
          接收数据
         
         
          Qt::AlignCenter
         
        
       
       
        
         
          Qt::Horizontal
         
         
          
           88
           20
          
         
        
       
      
     
     
      
       
        true
       
       
        
         261
         531
        
       
      
     
     
      
       
        
         
          Qt::Horizontal
         
         
          
           40
           38
          
         
        
       
       
        
         
          
           101
           41
          
         
         
          清空
         
        
       
       
        
         
          Qt::Horizontal
         
         
          
           30
           35
          
         
        
       
      
     
    
   
   
    
     
      1633
      690
      263
      271
     
    
    
     
      
       
        
         
          Qt::Horizontal
         
         
          
           40
           20
          
         
        
       
       
        
         
          
           76
           20
          
         
         
          
           宋体
           14
          
         
         
          发送数据
         
         
          Qt::AlignCenter
         
        
       
       
        
         
          Qt::Horizontal
         
         
          
           40
           20
          
         
        
       
      
     
     
      
       
        
         261
         191
        
       
      
     
     
      
       
        
         
          Qt::Horizontal
         
         
          
           40
           20
          
         
        
       
       
        
         
          
           101
           41
          
         
         
          发送
         
        
       
       
        
         
          Qt::Horizontal
         
         
          
           40
           20
          
         
        
       
      
     
    
   
  
  
   
    TopToolBarArea
   
   
    false
   
  
 
 
 
  
   QCustomPlot
   QWidget
   
qcustomplot.h
1

全篇完。

本人博客仅仅代表我个人见解方便记录成长笔记。

若有与 看官老爷见解有冲突,我坚信看官老爷见解是对的,我的是错的。

感谢~!

你可能感兴趣的:(QT,QT)