Wierd behavior with QSerialPort: readLine()

  • Hello,
    I hope i'm not making a fool of myself for asking a stupid Question.

    I'm using the QSerialPort in a Class to control a little robot via USB.
    The communication between robot and PC is simple.
    After receiving a command the robot, the robot executes the command.
    After that the robot sends a line with some data
    and an other line with an "OK" back.

    I wrote a little method which send a command and waits for an OK of the robot.
    I Init the serial port with

    if (!m_serial->open(QIODevice::ReadWrite))
        cout << "ERROR: Could not open serial port." << endl;
        return 0;

    string executeAndWait()

    string answer;
    QString temp = QString::fromStdString("M10");
    QByteArray command = temp.toLocal8Bit();
    m_serial->write( command);
    data = m_serial->readAll();
    if i use readLine or readAll doesnt change he result

    string check = data.toStdString() ;

    //check if end of answer reached, i knwo i know its not pretty...
    while(check.find("OK") == string::npos){
    data = m_serial->readAll();
    check = data.toStdString() ;


    I'm getting the output :
    M10 XY 300 380 0.00 0.00 A0 B0 H
    0 S95 U15 D60

    and i'm expecting
    M10 XY 300 380 0.00 0.00 A0 B0 H0 S95 U15 D60

    i did some testing and found out, there is always a cut after 32 Characters.
    I used other libraries for the communication before and had no issues what so ever.

    Im cluesless
    Please help

    If i haven't given you all the information you need please tell me

  • The problem is here:

    data = m_serial->readAll();

    ready read is emitted when some data can be read but that does not imply that all data can be read.

    see https://forum.qt.io/topic/70123/server-is-losing-bytes/3 , it's the same problem

  • Thank you for your answer, i tried to work with the Datastreams mentioned in the Example. It didn't work for me.
    In the end i wrote a little method which works.

    while(data.size() == avaiableBytes)

    is pretty much all i do.
    But I got one question left.

    Sometimes the '\n' is removed by readLine and sometimes it isnt. How does this happen.

    Cheers for the help much appreciation

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.