PDA

View Full Version : QextSerialPort with QTimer approch for reading



PaceyIV
16th May 2009, 11:07
Hi,

I try to emit a signal with the data actually received by QextSerialPort: something like the event DataReceived of C# .NET.

When I open the port I start a QTimer that every 100ms checks if there is byte available on the port and emit the signal with the data read.

My GUI freezes in this way :( If I block the sender device, my GUI exits from the freeze state and show some data.

Any ideas?

serialport.h


#include <QObject>
class QextSerialPort;
class QTimer;

class SerialPort : public QObject
{
Q_OBJECT

public:
SerialPort(QObject *parent = 0);
~SerialPort();

signals:
void receivedBytes(const QByteArray&, int);

public slots:
bool openPort();
void closePort();

private slots:
void checkRx();

private:
QextSerialPort *d_port;
QTimer *d_timer;
};


serialport.cpp


#include <QTimer>
#include <QDebug>
#include <qextserialport.h>
#include "serialport.h"

const int timeout = 100;

SerialPort::SerialPort(QObject *parent):
QObject(parent)
{
//modify the port settings on your own
d_port = new QextSerialPort("/dev/ttyUSB0");
d_port->setBaudRate(BAUD19200);
d_port->setFlowControl(FLOW_OFF);
d_port->setParity(PAR_NONE);
d_port->setDataBits(DATA_8);
d_port->setStopBits(STOP_1);

d_timer = NULL;
}

SerialPort::~SerialPort()
{
d_port->close();
delete d_port;
d_port = NULL;

d_timer->stop();
delete d_timer;
d_timer = NULL;
}

bool SerialPort::openPort()
{
bool state;
state = d_port->open(QIODevice::ReadWrite);

if (state)
{
if ( !d_timer )
{
d_timer = new QTimer(this);
connect(d_timer, SIGNAL(timeout()),
this, SLOT(checkRx()));
}
d_timer->start(timeout);
}
return state;
}

void SerialPort::closePort()
{
if (d_timer)
d_timer->stop();

d_port->close();
}

void SerialPort::checkRx()
{
int numBytes;

numBytes = d_port->bytesAvailable();

if (numBytes>0)
{
qDebug() << numBytes;

numBytes = (numBytes > 1024) ? 1024 : numBytes;

QByteArray bytes = d_port->read(numBytes);

emit receivedBytes(bytes, numBytes);
}
}

PaceyIV
18th May 2009, 15:33
I solved my problem by using 2 QThread instead of the QTimer.
Now I use my class MySerialPort with a thread for sending operation and another thread for receiving operation with the emission of the signal DataReceived like .NET.