PDA

View Full Version : Serial port timeout - Qextserialport



h-n-s
8th April 2013, 19:07
hello.
I want to write a program that will open the port and read data (in continuous mode, loop).

According to the algorithm:

Start ->
1.Try open port
a) if opened then read data
b) if not opened it wait 30 seconds and try to raise open port (jump to 1)


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


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
port = new QextSerialPort("/dev/ttyUSB0");
port->setBaudRate(BAUD9600);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_1);

port->setTimeout(500);
reading();

}

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



void MainWindow::reading()
{


qDebug() << port->open(QIODevice::ReadWrite);

if (port->isOpen()==false)
{
port->flush();

port->startTimer(30000);
qDebug() << "its it reading";
//port->waitForReadyRead(1000);
reading();
}
else
{
connect(port, SIGNAL(readyRead()), this, SLOT(onDataAvailable()));
}
}

void MainWindow::onDataAvailable()
{

if (port->isOpen())
{
QByteArray mdata = port->readAll();
qDebug() << "\n";

qDebug() << mdata.toHex(); // hex data
qDebug() << mdata; // ascii data



ui->lineEdit->clear();
ui->lineEdit->setText(mdata);
}
else
{

reading();
qDebug() << "error 2 port is not open";
}
// port->close();
}

Lesiok
9th April 2013, 06:42
First of all in method MainWindow::reading() if port->isOpen == false You have an infinite loop and stack overflow - You are calling reading in reading.
Second this all happens in the MainWindow constructor. By me it should be something like this :
#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
port = new QextSerialPort("/dev/ttyUSB0");
port->setBaudRate(BAUD9600);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_1);

port->setTimeout(500);
QTimer::singleShot(0,this,SLOT(reading()));

}

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



void MainWindow::reading()
{


qDebug() << port->open(QIODevice::ReadWrite);

if (port->isOpen()==false)
{
port->flush();

qDebug() << "its it reading";
QTimer::singleShot(30000,this,SLOT(reading()));
}
else
{
connect(port, SIGNAL(readyRead()), this, SLOT(onDataAvailable()));
}
}

void MainWindow::onDataAvailable()
{

if (port->isOpen())
{
QByteArray mdata = port->readAll();
qDebug() << "\n";

qDebug() << mdata.toHex(); // hex data
qDebug() << mdata; // ascii data



ui->lineEdit->clear();
ui->lineEdit->setText(mdata);
}
else
{

reading();
qDebug() << "error 2 port is not open";
}
// port->close();
}

To copy to clipboard, switch view to plain text mode
Of course raeding() should be declared as SLOT.