Serial GUI plot without timer

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtSerialPort/QSerialPort>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    QSerialPort *serial;
    QVector<double> dataArray;
    QVector<double> counterArray;
    double counter=0;

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

private:
    Ui::MainWindow *ui;

private slots:
    void readData();
    void on_btn_start_clicked();
    void on_btn_stop_clicked();
    void plot();
};

#endif // MAINWINDOW_H




mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPort>
#include <QDebug>
#include "qcustomplot.h"

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

    connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);

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

    //Setup plot
    ui->plot->addGraph();
    ui->plot->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); //point style in plot
    ui->plot->yAxis->setRange(0,10);
    ui->plot->xAxis->setRange(0,500);
}

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

void MainWindow::readData()
{

    char buffer[50];
    //QByteArray data = serial->readAll();
    double dataValue;
    serial->readLine(buffer, 50);
    sscanf(buffer,"%lf",&dataValue);
    if(counter<501)
    {
        counterArray.append(counter);
        counter++;
        dataArray.append(dataValue);
        plot();
    }
    else
    {
        dataArray.append(dataValue);
        dataArray.remove(0);
        plot();
    }

    //qDebug()<<dataValue;
    //console->putData(data);
}

void MainWindow::on_btn_start_clicked()
{
    serial->open(QIODevice::ReadWrite);
}

void MainWindow::on_btn_stop_clicked()
{
    serial->close();
}

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