我一直在掙扎着一個項目,它通過Qt中的串口進行通信大約兩週。首先我嘗試了信號/插槽方法,它錯過了一些數據。然後我決定用這個線程,但是我得到了相同的結果。當應用程序窗口被調整大小或最大化/最小化時,即使在窗口欄上按住鼠標左鍵,它也會錯過一些數據。請幫助我解決這個問題。帶線程的QSerialPort
的主窗口構造函數:
SerialPort *serial= new SerialPort();
serial->moveToThread(&cThread);
connect(this , &MainWindow::finished, &cThread, &QThread::quit);
connect(this , &MainWindow::destroyed, this, &SerialPort::deleteLater);
connect(serial, &SerialPort::getData, this, &MainWindow::displayData);
cThread.start();
串口讀取線程:
void SerialPort::newData()
{
mutex.lock();
bArray.insert(bArray.length(),serial->readAll());
mutex.unlock();
emit getData(&bArray,&mutex);
}
一個串口構造:
serial = new QSerialPort();
connect(serial, &QSerialPort::readyRead, this, &SerialPort::newData);
bArray.clear();
fill_serial_ports();
portName = find_stm32_port();
serial->setReadBufferSize(20*1024*1024); // it's a huge buffer.
bArray.reserve(20*1024*1024); // it's a huge buffer.
open_serial_port();
另外,我認爲這可能是一個錯誤是什麼錯過了一些數據並寫入了錯誤跟蹤器。受讓人說QSerialPort從來沒有丟失數據,我的代碼是錯誤的。我很困惑,我不知道在哪裏犯錯誤。請,你能檢查我的其他解決方案嗎?錯誤在哪裏?
我的bug跟蹤報告(不接受):https://bugreports.qt.io/browse/QTBUG-61233
請問一些示例代碼? –
偏離主題,但是......如果你的單線程代碼缺少來自端口的數據,那麼我不禁感覺到將該代碼移動到另一個線程只會使*真實*問題更難調試。 –
如果您要從串口接收大量數據,您可能需要累積從幾個readyRead信號接收到的數據。 – Jeka