Search code examples
c++qtserial-portqt5timing

How can I insert gaps into serial communication?


An old application made with Qt4 communicates with an external device via a serial port, and I would like to port it to Qt5.

To synchronize the device, a gap is inserted between data packages:

(Inside the run() method in a class derived from QThread)

QSerialPort *serial;

// setting up the serial port  
// ....

for (...)
{
    serial->write(data, length);
    serial->flush();
    this->msleep(pause); 
}

where pause is longer than the time needed by the writing, to guarantee a gap.

This all worked fine under Qt4, but it doesn't work on Qt5.

serial->flush(); causes the whole communication to hang (and never recover) after the first data package, so I removed it.

The sleeping has no effect. Neither this->msleep(pause); nor QThread::msleep(pause); work, the data packages are just glued together. This is highly likely to be caused by the removal of flushing, the actual data is only sent after enough bytes are gathered in the buffer.

I guess a working solution would be to no longer use a class derived from QThread, but use a QObject with moveToThread(), set up a bunch of signals and slots, and use a QTimer for the timing.

However, this would result in rebuilding a large part of the application from scratch. Is there a better way?


Solution

  • Replacing serial->flush(); with serial->waitForBytesWritten(); solved the problem.

    It seems that some of the interactions between the serial communication and the event loop have been changed between Qt4 and Qt5.