Can QSerialPort read more than 512 bytes of data?

前端 未结 2 1448
温柔的废话
温柔的废话 2021-01-28 06:28

I want to use QSerialPort to read data transmitted from a device. The device transmits a frame of 4000 data bytes each time. I try with the following simple code



        
相关标签:
2条回答
  • 2021-01-28 06:54

    There's no limit, but you don't necessarily receive all data in single chunk. You have to keep listening until you have the number of bytes you're waiting for (or a timeout).

    void MainWindow::serialReceived()
    {
        receivedData.append(serialPort->readAll());
        if(receivedData.size() >= 4000) {
           // we're full
        }
    }
    
    0 讨论(0)
  • 2021-01-28 07:00

    You generally have to read out the data in a loop (to ensure you get it all), here is a snippet of example code this is equivalent to your serialReceived() function, except it emits the data using emit rxDataReady(newData); to whoever is listening...

    void QSerialPortReader::handleReadyRead()
    {
        QByteArray newData;
    
        // Get the data
        while (mp_serialPort->bytesAvailable())
        {
            newData.append(mp_serialPort->readAll());
        }
        emit rxDataReady(newData);
    }
    

    edit

    Although I don't do any max size checking... but that is trivial to add if you need it (i.e. just use read(..., spaceAvail) instead of readAll and then decrement spaceAvail...

    0 讨论(0)
提交回复
热议问题