2013-07-17 31 views
3

我正在从串口读取信息。我如何等待换行符进入,然后处理数据?也就是说,我如何确保我一次能够完成整条生产线。Qt QSerialPort缓冲

此代码不起作用:

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 = ""; 
    } 
} 

比方说串行端口发送 “传感器1 200 \ n”。
数据可能包含以下内容:“Se”然后“n”,“sor 2”“00 \ n”等。

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

附加信息:
READDATA被设置为一个槽:

connect(serial, SIGNAL(readyRead()), this, SLOT(readData())); 
+1

这不是(几乎)你的代码做什么?除了如果在一次readData()调用中收到“200 \ nSensor5”,“Sensor5”部分将作为上一行的一部分传递给parseData,并且不会包含在发送到下一行的开始行parseData – Pete

+0

当你说'这段代码不起作用'你输出了什么? – Pete

+0

我得到上面的混合输出。通过canReadLine()获得解决方案:block; – Dirk

回答

3

难道你没有使用一个串口的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

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