我从串行端口(在 Qt 中,使用 QtSerialPort/QSerialPort)读取的数据由换行符 '\n' 分隔并返回 '\r' 字符,这是我打算解析它的方式.行的长度可能会很长,但是很容易从每行的格式中提取数据。
//signal/slot connection on readyRead() is as follows:
connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
其中 readData() 定义为:
void MainWindow::readData()
{
//As mentioned below, which I will reiterate, I have already tried the addition of
// canReadLine():
if (serial->canReadLine()){
QByteArray data = serial->readLine();
//QByteArray allData = serial->readAll();
parseSerialBytes(data);
//console->putData(data);
//console->putData(alldata);
}
}
但是,QIODevice::readLine()
函数非常慢,并且与 QIODevice::readAll() 相比,显然会阻止以全频率接收数据
谁能解释一下如何正确使用 readLine()
函数,这样我就不必通过 readAll()
循环到 QByteArray
解析每一行?我使用“终端”Qt Widgets 示例来创建此异步串行端口读取功能。
提前致谢 - 这似乎是一个常见问题,我还没有在这里看到答案。
最佳答案
这是一个常见错误。 readData
仅每 block 数据调用一次,不一定每行一次。
只要数据可用,您就需要继续读取行。在小部件类中读取串行线也是一个糟糕的设计。将其移至单独的对象。
class Receiver : public QObject {
Q_OBJECT
QSerialPort m_port;
QByteArray m_buffer;
void processLine(const QByteArray & line) {
...
}
Q_SLOT void readData() {
// IMPORTANT: That's a *while*, not an *if*!
while (m_port.canReadLine()) processLine(m_port.readLine());
}
public:
Receiver(QObject * receiver = 0) : QObject(parent) {
connect(&m_port, &QIODevice::readyRead, this, &Receiver::readData);
...
}
}
您的错误是如下所示实现 readData
。无论有多少行可供读取,此类代码都只读取一行。它会显得“慢”,因为每次调用都会有越来越多的未读累积数据。最终它会耗尽堆。
void readData() {
// WRONG!
if (m_port.canReadLine()) processLine(m_port.readLine());
}
关于c++ - QSerialPort readLine() 与 readAll() 相比非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24768916/