Qt QSerialPort缓冲

时间:2013-07-17 15:11:56

标签: c++ qt

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

此代码不起作用:

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

2 个答案:

答案 0 :(得分: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 
       }
 }

答案 1 :(得分:1)

创建一个静态变量,然后存储数据,直到获得 \ 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
}