Can QSerialPort read more than 512 bytes of data?

2020-05-07 08:04发布

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

QSerialPort *serialPort;
char receivedData[4000];
int numRead = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /* Initialize serial port*/
    serialPort = new QSerialPort(this);
    QString portName = "COM6";
    qint32 baudRate = 460800;
    serialPort->setPortName(portName);
    serialPort->setBaudRate(baudRate);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    serialPort->setReadBufferSize(4000);
    if (!serialPort->open(QIODevice::ReadOnly)) {
        qDebug() << "Cannot open comport";
    }
    connect(serialPort, SIGNAL(readyRead()), this, SLOT(serialReceived()));
}

void MainWindow::serialReceived()
{
    numRead = serialPort->read(receivedData, 4000);
    serialPort->flush();
}

The problem is: it always shows that only 512 data bytes are read. How can I read the whole 4000 bytes data frame? (when I'm using Matlab to read this 4000 bytes frame, it's working fine)

2条回答
走好不送
2楼-- · 2020-05-07 08:23

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
    }
}
查看更多
放我归山
3楼-- · 2020-05-07 08:25

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...

查看更多
登录 后发表回答