Qt QSerialPort缓冲 [英] Qt QSerialPort buffering

查看:2565
本文介绍了Qt QSerialPort缓冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am reading information from a serial port. How do I wait for a newline to come in, and then deal with the data? That is, how do I make sure I'm chunking a whole line at a time.

此代码无效:

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 200 \\\
等。

Let's say the serial port sends "Sensor1 200\n".
data might contain the following: "Se" then "n", "sor 2" "00\n" and so on.

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

How do I block calling parseData until I have a line of text?

其他信息:

readData设置为插槽:

Additional info:
readData is set up as a slot:

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


推荐答案

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

Have you not tried using the SerialPort readLine() function? after each readline(), you can send the line to some new ByteArray or QString to be parsed up. I also use .trimmed() on the end to remove the '\r' and '\n' characters, so I can do something like so:

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 
       }
 }

这篇关于Qt QSerialPort缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆