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

    m_serial->setPortName("ttyUSB0");
    if (!m_serial->open(QIODevice::ReadWrite))
    {
    
        cout << "ERROR: Could not open serial port." << endl;
        return 0;
    }
    m_serial->setBaudRate(m_serial->Baud115200);
    m_serial->setStopBits(m_serial->OneStop);
    m_serial->setFlowControl(m_serial->NoFlowControl);
    m_serial->setParity(m_serial->NoParity);
    m_serial->setDataBits(m_serial->Data8);
    m_serial->setReadBufferSize(0);
    m_serial->flush();
    

    string executeAndWait()
    {

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

    string check = data.toStdString() ;
    cout<<check<<endl;

    //check if end of answer reached, i knwo i know its not pretty...
    while(check.find("OK") == string::npos){
    m_serial->waitForReadyRead(100000000);
    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
    OK

    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

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



  • The problem is here:

    m_serial->waitForReadyRead(100000000);
    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.