2013-11-20 47 views
1

我試圖從單獨的線程讀取/寫入數據。打開串口時不顯示錯誤,但我無法讀取或寫入任何內容。在單獨的線程上使用QSerialPort

這是我SerialThread.h代碼:

#include <QThread> 

class SerialThread : public QThread 
{ 
    Q_OBJECT 
public: 
    explicit SerialThread(QObject *parent = 0); 
    ~SerialThread(); 

protected: 
    void run(); 
private: 
    bool _threadRunning; 
}; 

而且我SerialThread :: run()的實現:

void SerialThread::run() 
{ 
    QSerialPort *_serial = NULL; 
    foreach(QSerialPortInfo info, QSerialPortInfo::availablePorts()) 
    { 
     QString name = info.portName(); 
     if(name.startsWith("usbserial-")) 
     { 
      _serial = new QSerialPort(info, this); 

      qDebug() << "Opening " << name; 
      if(_serial->open(QSerialPort::ReadWrite)) 
      { 
       qDebug() << "ok"; 
       _threadRunning = true; 
      } 
     } 
    } 

    while(_threadRunning) 
    { 
     QByteArray array = _serial->read(10); 
     for (int i = 0; i< array.length(); i++) 
      qDebug() << QString::number(array[i], 16); 
     msleep(1000); 
    } 

    if(_serial) 
    { 
     _serial->close(); 
     delete _serial; 
    } 
} 

相同的代碼工作無螺紋(連接readyReady()信號)。

有什麼想法?我可能會濫用QThread對象嗎?

回答

1

read()實際上並沒有做任何的閱讀和需要一個事件隊列在緊要關頭才能正常

你可以叫_serial->waitForReadyRead()每當_serial->bytesAvailable()是0