QThread中的QSerialPort

时间:2018-01-29 10:35:55

标签: qt serial-port qthread

我试图从线程中读取串行输出。串口在主程序中打开,并将QSerialPort变量传递给线程。

然后我在线程中调用serial.waitForReadyRead()函数,但它没有从串口获取任何值。我确认串口正在通过从主程序中读取数据来发送数据。

有谁知道为什么会发生这种行为?

添加以下代码:

mainwindow.h

    class MainWindow : public QMainWindow
    {
        Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
        QSerialPort *serial;
    private slots:
        void onProgressChanged();
    private:
        Ui::MainWindow *ui;
    };



    class WorkerThread : public QThread {
        Q_OBJECT
        public:
            QSerialPort *thread_serial;

            void run() {
                int ret = thread_serial->waitForReadyRead(60000);  //thread is not getting any serial data. 
                                                                   //so it will not emit progressChanged.
                if (ret)
                {
                    qDebug()<<"Data Rate Read done";
                    QByteArray recvData = thread_serial->readAll();
                    qDebug()<<recvData;
                    emit progressChanged();
                }
            }
            // Define signal:
            signals:
            void progressChanged();
    };

mainwindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    serial = new QSerialPort(this);

    openSerialPort( );
}

void MainWindow::openSerialPort( )
{
    serial->setPortName("COM 4");
    serial->setBaudRate(QSerialPort::Baud115200);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    if (serial->open(QIODevice::ReadWrite)) {

        qDebug()<<"Connected";

        WorkerThread *workerThread = new WorkerThread();
        workerThread->thread_serial = serial;
        connect(workerThread, SIGNAL(progressChanged()),
                                      SLOT(onProgressChanged()));
        workerThread->start();

    }
}

void MainWindow::onProgressChanged()
{
    qDebug()<<"inside onProgressChanged";
}

0 个答案:

没有答案