c++ - How do I collect real time data of an external serial device in Qt Creator? -
i trying collect real time info arduino (using qt class qserialport) , plot in real time graph (using class qcustomplot). new using serial devices i'm not sure function utilize in qserialport class collect data. below current code of how set serial:
qserialport serial; mainwindow::mainwindow(qwidget *parent) : qmainwindow(parent), ui(new ui::mainwindow) { ui->setupui(this); serial.setportname("com4"); serial.setbaudrate(qserialport::baud9600); serial.setdatabits(qserialport::data8); serial.setparity(qserialport::noparity); serial.setstopbits(qserialport::onestop); serial.setflowcontrol(qserialport::noflowcontrol); serial.open(qiodevice::readwrite); setuprealtimedatademo(ui->customplot); }
...and here code real time slot data...
void mainwindow::realtimedataslot() { // calculate 2 new info points: #if qt_version < qt_version_check(4, 7, 0) double key = 0; #else double key = qdatetime::currentdatetime().tomsecssinceepoch()/1000.0; #endif static double lastpointkey = 0; if (key-lastpointkey > 0.01) // @ add together point every 10 ms { double value0 = qsin(key); //sin(key*1.6+cos(key*1.7)*2)*10 + sin(key*1.2+0.56)*20 + 26; double value1 = qcos(key); //sin(key*1.3+cos(key*1.2)*1.2)*7 + sin(key*0.9+0.26)*24 + 26; // add together info lines: ui->customplot->graph(0)->adddata(key, value0); ui->customplot->graph(1)->adddata(key, value1); // set info of dots: ui->customplot->graph(2)->cleardata(); ui->customplot->graph(2)->adddata(key, value0); ui->customplot->graph(3)->cleardata(); ui->customplot->graph(3)->adddata(key, value1); // remove info of lines that's outside visible range: ui->customplot->graph(0)->removedatabefore(key-8); ui->customplot->graph(1)->removedatabefore(key-8); // rescale value (vertical) axis fit current data: ui->customplot->graph(0)->rescalevalueaxis(); ui->customplot->graph(1)->rescalevalueaxis(true); lastpointkey = key; } // create key axis range scroll info (at constant range size of 8): ui->customplot->xaxis->setrange(key+0.25, 8, qt::alignright); ui->customplot->replot(); // calculate frames per second: static double lastfpskey; static int framecount; ++framecount; if (key-lastfpskey > 2) // average fps on 2 seconds { ui->statusbar->showmessage( qstring("%1 fps, total info points: %2") .arg(framecount/(key-lastfpskey), 0, 'f', 0) .arg(ui->customplot->graph(0)->data()->count()+ui->customplot->graph(1)->data()->count()) , 0); lastfpskey = key; framecount = 0; } }
any help on how info in real time and/or improve implementation appreciated. :)
you can connect readyread
signal of qserialport
slot read info whenever new info has arrived :
connect(serial, signal(readyread()), this, slot(readdata()));
in readdata
can phone call readall()
read available info qbytearray
, pass array function plot :
void mainwindow::readdata() { qbytearray info = serial->readall(); plotmydata(data); }
c++ qt serial-port real-time qt-creator
No comments:
Post a Comment