Qt 串口使用

Qt串口所属文件“qextserilport.h”


常用设置接口:

setBaudRate( BAUD115200 );
setFlowControl( FLOW_OFF );
setParity( PAR_NONE );
setDataBits( DATA_8 );
setStopBits( STOP_1 );

简单使用:

.h

class SerialTest : public QThread {
    Q_OBJECT
  public:
    static SerialTest *getInstance() {
        if ( !instance ) {
            instance = new SerialTest ;
        }
        return instance;
    };
    void                      initSerial();
    static QextSerialPort     *serialChannel;
    static void               notifyHandler();

  signals:
    void serialData( QString );

  private:
    static SerialTest *instance;
};

.cpp

SerialTest *SerialTest::instance              = nullptr;
QextSerialPort     *SerialTest::serialChannel = nullptr;
static const QString    testPortDevice{"/dev/ttyACM0"};

void SerialTest::initSerial() {
    serialChannel = new QextSerialPort( testPortDevice);
    connect( serialChannel , &QextSerialPort::readyRead,
             &SerialTest::notifyHandler );
    qDebug() << "init.";
}

void SerialTest::notifyHandler() {
    QString recieveData =
        QString::fromUtf8( serialChannel ->readAll() ).simplified();
    if ( !recieveData.isNull() ) {
        qDebug() << "RECEIVE SERIAL DATA:" << recieveData << endl;
        emit instance->serialData( recieveData );
    }
}

其中,/dev/ttyACM0"是虚拟串口设备,真实串口更改对应的端口号及设置。

你可能感兴趣的:(Qt,qt,开发语言)