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
}
}
相关文章