Search code examples
qtqt5qtserialport

Qt5 QSerialPort write data


How I can write data in serial port, with delay between send's messages? This is my code:

void MainWindow::on_pushButton_Done_clicked()
{
    if(sport->isOpen()){
        sport->clear();
        QString cmd = Phase+Mode;

        //Write Stop
        sport->write("stop!", 5);

        //Write Mode
        sport->write(cmd.toStdString().c_str(), cmd.toStdString().length());

        //Write Speed
        sport->write(Speed.toStdString().c_str(), Speed.toStdString().length());

        //Write Direction
        sport->write(Direction.toStdString().c_str(), Direction.toStdString().length());

        //Run
        sport->write("start!", 6);

    }
}

My device receives an error message when I call this function.

Thank you.


Solution

  • 2 options:

    • use waitForBytesWritten to ensure the bytes are written and then a short sleep

      however this will block the thread and will block the gui

    • the other is using a QTimer to trigger another slot a few times and a field that will indicate what needs to be sent