QSerialPort 可以读取超过 512 字节的数据吗? [英] Can QSerialPort read more than 512 bytes of data?

查看:34
本文介绍了QSerialPort 可以读取超过 512 字节的数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 QSerialPort 读取从设备传输的数据.设备每次传输 4000 个数据字节的帧.我尝试使用以下简单代码

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();
}

问题是:它总是显示只读取了 512 个数据字节.如何读取整个 4000 字节的数据帧?(当我使用 Matlab 读取这 4000 字节的帧时,它工作正常)

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)

推荐答案

没有限制,但您不一定会在单个块中接收所有数据.您必须继续收听,直到获得等待的字节数(或超时).

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

这篇关于QSerialPort 可以读取超过 512 字节的数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆