QT串口编程--多线程

最近在做项目,用到了QT的串口编程,参考http://blog.csdn.net/yafeilinux/article/details/4717706

在虚拟机里做好了软件,在ARM上跑有卡顿的现象,果断用多线程解决。

贴一下主要的代码

自定义线程类,基类QThread

class MyThreadSerial : public QThread
{
    Q_OBJECT
public:
    MyThreadSerial(QObject *parent = 0)
           : QThread(parent)
       {
       }
protected:
    void run();
public:
    volatile bool stopped;
public:
    void ThreadopenMycom();
    Posix_QextSerialPort *ThmyCom;
signals:
     void ThreadMyCom(const QString &);
};

widget类里面定义一个槽,这个是我用来判断发来的数据并把数据显示在界面上。

private slots:
                    void readMyCom(const QString &);
public:
		    MyThreadSerial* serial;       



==============================================

在widget.cpp中:

构造函数添加代码:

 serial = new MyThreadSerial(this);
 connect(serial,SIGNAL(ThreadMyCom(QString)),this,SLOT(readMyCom(QString)));


void MyThreadSerial::run()
{
    ThmyCom = new Posix_QextSerialPort("/dev/ttySAC3",QextSerialBase::Polling);
    ThmyCom->open(QIODevice::ReadWrite);
    ThmyCom->setBaudRate(BAUD38400);
    ThmyCom->setDataBits(DATA_8);
    ThmyCom->setParity(PAR_NONE);
    ThmyCom->setStopBits(STOP_1);
    ThmyCom->setFlowControl(FLOW_OFF);
    ThmyCom->setTimeout(10);

    while(stopped)
    {
        QString str = ThmyCom->readAll();
        emit ThreadMyCom(str);
        msleep(10);
    }
    stopped = false;
}
void Widget::readMyCom(const QString &str)
{
  .......
}
 
  
 测试后,运行正常! 
  


你可能感兴趣的:(Qt)