2017-08-04 31 views
0

我正在研究Qt,但是我遇到了一個問題,對於我來說我無法修復。我已經嘗試了很多不同的組合,但是它仍然沒有給我輸出我想要的。我希望有人能幫助我。Qt讀取串行輸入,然後將其分割成單獨的變量

QStringList buffer_split = serialBuffer.split(","); // split the serialBuffer string, parsing with ',' as the separator 

    // Check to see if there less than 3 tokens in buffer_split. 
    // If there are at least 3 then this means there were 2 commas, 
    // means there is a parsed temperature value as the second token (between 2 commas) 
    if(buffer_split.length() < 3){ 
     // no parsed value yet so continue accumulating bytes from serial in the buffer. 
     serialData = arduino->readAll(); 
     serialBuffer = serialBuffer + QString::fromStdString(serialData.toStdString()); 
     serialData.clear(); 
    }else{ 
     // the second element of buffer_split is parsed correctly, update the temperature value on temp_lcdNumber 
     serialBuffer = ""; 
     qDebug() << buffer_split << "\n"; 
     parsed_data = buffer_split[1]; 

} 

上述解決方案已經爲我工作,反過來我正在讀的值通過串口發送如:

0,0,0,0,0,0 

以上就是如何parsed_data正在讀從串口信息, 哪個是對的。

我遇到的問題是分裂,然後將它們存儲在單獨的變量中以啓動一些if語句。到目前爲止,我似乎無法得到它的工作。

如果有人可以幫助我,我將不勝感激

謝謝

+0

我不清楚你的問題。正如你用parsed_data = buffer_split [1]寫的那樣,你可以訪問每個單獨的值並存儲它。你卡在哪裏? –

+0

當我嘗試存儲例如buffer_split [2]時,它似乎不起作用。尋找這樣的東西。我希望這可以讓你更容易理解。例如im發送的數組是45,0,67,0,0,13,我需要將每個數字存儲在一個變量中。 int num1 = parsed_data [0]這將是45,詮釋num2 = parsed_data [1]這將是0和詮釋num3 = parsed_data [2]這將是67 –

回答

0

你並不需要一個額外的parsed_data變量buffer_split存儲它們,你只需要int num1 = buffer_split[0].toInt(); int num2 = buffer_split[1].toInt(); ...

+0

嗨,我以前嘗試過,但值只是保持零即使他們改變了。 'num1 = parsed_data.mid(0,1).toInt();'似乎工作,但我相信這是不正確的方式來解決它。 –

+0

嘿我迷惑了一下。你能否讀取原始數據,如4,0,2,5,7,1,如果你不能從串行端口讀取問題而不是拆分值。嘗試以\ n換行符結尾發送值,並在收到全行時讀取它,您可以使用canReadLine()函數進行檢查 – onurozturk

相關問題