Problem with receiving solid length array of data in QSerialPort in readyRead SLOT



  • Hey guys,

    in my application I am trying to receive simple array of bytes from external device.

    QSerialPort setup below

    SP1 = new QSerialPort(this);
        connect(SP1, &QSerialPort::readyRead, this, &Master::ReadSerial);
    
        SP1->setPortName("ttyACM0");
        SP1->setBaudRate(250000);
        SP1->setDataBits(QSerialPort::Data8);
        SP1->setParity(QSerialPort::NoParity);
        SP1->setStopBits(QSerialPort::OneStop);
        SP1->setFlowControl(QSerialPort::NoFlowControl);
    
        if(SP1->open(QIODevice::ReadWrite))
        {
            Console("SP OPENED");
        }
    

    The data received should look like this "<#____________________>".
    The starting character is '<' the terminating character is '>' and the second character is always '#'. Everything between varies.

    I have tried different ways from long byte by byte checking routine to simplest readAll then parse way. Everytime was the problem that in one call of readyRead it hasnt loaded whole "packet". Almost every time it has split it into at least two parts.
    I have increased Baud rate to 250 000 bps, nothing changed.

    My current code looks like this, i am able to catch the string in case the '<' character is the first ever character received since start of the app.

    void Master::ReadSerial()
    {
        SERIAL_PACKET_OK = false;
        TmpRx = SP1->readLine(1);
        while(TmpRx[0] != '$')
        {
            TmpRx = SP1->readLine(1);
        }
        RxBuffer = SP1->readLine(23);
        RxTimeout = 100000;
        while(RxBuffer.length() < 23 && RxTimeout--)
        {
            RxBuffer += SP1->readAll();
        }
        if(RxBuffer[0] == '$' && RxBuffer[1] == '#' && RxBuffer[22] == '>')
        {
            Console("Packet ok?");
            SERIAL_PACKET_OK = true;
        }
        Console(QString(RxBuffer));
    
    }
    

    I will take a look at it tomorrow again but every help/hint will be highly appreciated.

    Pete


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Changing the speed of your serial port won't help size wise, your computer won't change his based on the speed you set.

    In any case, what is usually that is that you cumulate the data that have arrived when readyRead has been called in a buffer and then parse that buffer and only act if you have what you want in it.

    So basically:

    RxBuffer += SP1->readAll();
    if (conditions_you_want) {
       // calculate start + length
        QByteArray packet = RxBuffer.right(start, length);
        RxBuffer.remove(start, length);
        // Do some processing with packet
    }
    

Log in to reply
 

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