4

我正在从串行端口读取信息。我如何等待换行符进来,然后处理数据?也就是说,我如何确保一次分块整行。

此代码不起作用:

void MainWindow::readData()
{
    QByteArray data = serial->readAll(); //reads in one character at a time (or maybe more)
    console->putData(data); 
    charBuffer.append(data); 
    if (data.contains("\n")) //read into a structure until newline received.
    {
        //call parsedata
        sensorValues->parseData(charBuffer); //send the data to be parsed.
        //empty out the structure
        charBuffer = "";
    }
}

假设串口发送“Sensor1 200\n”。
数据可能包含以下内容:“Se”然后是“n”、“sor 2”、“00\n”等等。

如何阻止调用 parseData 直到我有一行文本?

附加信息:
readData 设置为插槽:

    connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
4

2 回答 2

3

您没有尝试过使用 SerialPort readLine() 函数吗?在每个 readline() 之后,您可以将该行发送到一些新的 ByteArray 或 QString 以进行解析。我还在末尾使用 .trimmed() 来删除 '\r' 和 '\n' 字符,所以我可以这样做:

void MainWindow::readData()
{
    while (serial->canReadLine()){
       QByteArray data = serial->readLine();   //reads in data line by line, separated by \n or \r characters
       parseBytes(data.trimmed()) ;
     }
}

 void MainWindow::parseBytes(const QByteArray &data) <--which needs to be moved to       separate class, but here it's in the MainWindow, obviously improper
 {
       if (data.contains("1b0:"))
       {
            channel1Data.b0_code = data.mid(5);   // which equals "1", 
            //do stuff or feed channel1Data.b0_code to a control 
       }
 }
于 2014-07-23T20:59:49.207 回答
2

创建一个静态变量,然后存储数据,直到你得到一个\n

void readData()
{
    // Read data
    static QByteArray byteArray;
    byteArray += pSerialPort->readAll();

    //we want to read all message not only chunks
    if(!QString(byteArray).contains("\n"))
        return;

    //sanitize data
    QString data = QString( byteArray ).remove("\r").remove("\n");
    byteArray.clear();

    // Print data
    qDebug() << "RECV: " << data;

    //Now send data to be parsed
}
于 2017-06-16T16:52:30.500 回答