SerialGUI with fast display

1) Add Qcustomplot.h and qcustomplot.cpp to project
2) QT += core gui serialport printsupport in .pro file

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSerialPort>
#include <QDebug>
#include<QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    QTimer *dataCaptTimer;
    QSerialPort serial;
    QVector<double> dataArray;
    QVector<double> CounterArray;
    double count=0;

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

private slots:
    void on_start_btn_pressed();

    void on_stop_btn_pressed();

private:
    Ui::MainWindow *ui;

public slots:
    void startDataCapture();
    void plot();
};

#endif // MAINWINDOW_H


mainwindow.cpp

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    dataCaptTimer=new QTimer;
    dataCaptTimer->setInterval(1);  //the setInterval() determines how fast is your display
    connect(dataCaptTimer,SIGNAL(timeout()),this,SLOT(startDataCapture()));

    ui->setupUi(this);

    serial.setPortName("COM6");
    serial.setBaudRate(QSerialPort::Baud115200);
    serial.setDataBits(QSerialPort::Data8);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
    serial.setParity(QSerialPort::NoParity);

    ui->plot->addGraph();
    ui->plot->yAxis->setRange(0,10);
    ui->plot->xAxis->setRange(0,50);
    ui->plot->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
}

MainWindow::~MainWindow()
{
    serial.close();
    delete ui;
}

void MainWindow::on_start_btn_pressed()
{    
    startDataCapture();
}

void MainWindow::on_stop_btn_pressed()
{
     serial.close();
     //dataArray.clear();
     //CounterArray.clear();
     dataCaptTimer->stop();
}

void MainWindow::startDataCapture()
{
    dataCaptTimer->stop();
    serial.open(QIODevice::ReadWrite);
    char buffer[50];
    double dataValue;
    serial.waitForReadyRead();
    serial.readLine(buffer, 50);
    sscanf(buffer,"%lf",&dataValue); //Convert string to integer
    if(count<51)
    {
        count++;
        dataArray.append(dataValue);
        CounterArray.append(count);
        plot();
    }
    else
    {
        dataArray.remove(0);     //Remove the first element so that plot appears scrolling
        dataArray.append(dataValue); //Add the new data at the end
        CounterArray.append(count);
        plot();
    }
    qDebug()<<dataArray;
    dataCaptTimer->start();
}

void MainWindow::plot()
{
    ui->plot->graph(0)->setData(CounterArray, dataArray);
    ui->plot->replot();
    ui->plot->update();
}




Comments

Popular posts from this blog

HackRF with srsLTE and openlte

Blinking a LED in STM32F103C8T6 (Blue Pill) Board

Read Continuously from Serial Port in QT