Solved SerialPort send each byte with delay
-
Hi, I need an advice.
I need to send some bytes by serialport, but with 5ms of delay between each byte sent.
I tried this solution, but obviously don't work:QByteArray s = "1234567980"; for(int i = 0; i < s.lenght(); <++) { SerialPort.write(s[i], 1); QThread::msleep(5); }
I haven't ideas.
Can you help me?
Thanks. -
@Stefanoxjx said in SerialPort send each byte with delay:
QThread::msleep(5);
Never do this in event driven applications!
Use a QTimer with 5ms timeout and send inside the slot connected to the timer. -
-
@Stefanoxjx This cannot work, because you are locking the main thread, you have to give QSerialPort "time to work".
QByteArray s = "1234567980"; for(int i = 0; i < s.lenght(); <++) { SerialPort.write(s[i], 1); if(!SerialPort.waitForBytesWritten()) qDebug() << "Failed to write on serial port!"; QThread::msleep(5); }
take a look at documentation ==> https://doc.qt.io/qt-5/qserialport.html#waitForBytesWritten
-
@SGaist: I must send command strings to an external device, but for sure it has a bad management of the serial port, because without delay it losts many bytes.
Thanks at all for help (I hoped there was a more direct solution then QTimer)
-
@Stefanoxjx said in SerialPort send each byte with delay:
I hoped there was a more direct solution then QTimer
QTimer is not required in this case, you can do it in "polling mode". But you have to call
QSerialPort::waitForBytesWritten()
to give QSerialPort time to send the data.
CallingQSerialPort::write()
will only put data into the output buffer, not sending the data on serial port.
Or you have to do it asynchronously, with a QTimer.Booth solutions are valid, it is up to you.
-
Hi @Stefanoxjx
Like @SGaist, I believe msleep and usleep are very bad ideas. The waitForBytesWritten can work but is not as flexible in the event driven system. I like using a single-shot QTimer (0 for the time) to run a state machine in my apps when sending a command. The next state is initiated by the reply. I also keep a no-data QTimer with a 1.5sec timeout for when the reply is delayed to resend the command.
This really works fast, is reliable, scalable, and ports well to its own thread or in the main thread. -
I tryed WaitForBytesWritten, but doesn't work.
QTimer solve the problem very well :)