c++qtserial-portqtserialport

How can I wait for all data to be written before the serial port connection is terminated


I need to send data from my QT application via serial port. I am trying to send data in this way.

void productDetail::on_detailSaveBtn_clicked()
{
    if (!serial.isOpen())
    {
        if (serial.begin(QString("COM3"), 9600, 8, 0, 1, 0, false))
        {
            serial.send(ui->productDesp->text().toLatin1());
            serial.end();
        }
    }
}

As I understand it, serial connection closes without writing all data. I think closing the serial port after waiting for all the data to be written can solve my problem. How can I verify that all data is written before the serial port close?

QT 5.15.2 Windows


Solution

  • Try to wait a few time so a portion of data can be written. Check if any left with while loop and repeat the process.

    serial.send(ui->productDesp->text().toLatin1());
    while(serial.bytesToWrite()){
        serial.waitForBytesWritten(20);
    }
    serial.end();