qt界面-串口

遇到的坑

1.使用類的時候必須要new,不然會有錯誤。

my_qserial *local_serial;
local_serial = new my_qserial();

2.未知長度數組問題,弄好久,還是用已知長度去定義的。調試代碼也花費了好久的時間。

3.QByteArray 數組問題,使用很方便,但有些地方不能當作數組使用。

QByteArray data = port->readAll();
 if((data.at(0) == '\xdf'))

4.花費時間最久的是串口和線程的問題,這是使用的串口的一種方法,但是會有線程之間的錯誤問題

my_qserial::my_qserial(QObject *parent) : QObject(parent)
{
    my_thread = new QThread();
    show_func_id();
    show_slots_id();
    port = new QSerialPort();
    init_port();
    //this->moveToThread(my_thread);
    port->moveToThread(my_thread);
    my_thread->start();//開啓多線程
    qDebug() << "in main thread";
    //接收到數據就觸發
    connect(port,SIGNAL(readyRead()),this,SLOT(handle_data()),Qt::DirectConnection);
    
}

//初始化串口
void my_qserial::init_port()
{
    port->setPortName("COM3");
    port->setBaudRate(19200);
    port->setDataBits(QSerialPort::Data8);
    port->setParity(QSerialPort::NoParity);
    port->setStopBits(QSerialPort::OneStop);
    port->setFlowControl(QSerialPort::NoFlowControl);
    if(port->open(QIODevice::ReadWrite))
    {
        qDebug() << "Port have been opened";
    }
    else
    {
       qDebug() << "open it failed";
    }
}
UIDemo01::UIDemo01(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UIDemo01)
{
    ui->setupUi(this);
    this->initForm();
    local_serial = new my_qserial();
    timer = new QTimer;
    mutex = new QMutex; //添加互斥鎖
    qDebug() << "main thread:" << QThread::currentThreadId();
    //查看線程號
    connect(local_serial,SIGNAL(thread_sig()),this,SLOT(sig_slot()),Qt::DirectConnection);
    //接收到數據就觸發
    connect(local_serial,SIGNAL(interrupt_function()),this,SLOT(slots_interrupt_function()),Qt::DirectConnection);
    //版本號查詢
//    local_serial->sedata[0] =0x00;
//    local_serial->write_data(
//                local_serial->data(char(0x00),char(0x00),1,local_serial->sedata),1+15);
//    local_serial->Send_number_flag +=1;//發送一個數據加一次
    connect(timer, SIGNAL(timeout()), this, SLOT(slots_send_version()),Qt::DirectConnection);
       timer->start(20000); // 每隔1s
}

5.connect函數最後一個參數問題。信號與槽的連接方式問題。

信號與槽的連接方式 有如下幾種

       - Qt:: DirectConnection (立即調用) 

       - Qt::QueuedConnection (異步調用) 

       - Qt::BlockingQueuedConnection (同步調用) 

       - Qt: :AutoConnection (默認連接) 

       - Qt:: UniqueConnection (單一連接) 

詳細參見:https://blog.csdn.net/qq_39654127/article/details/81988281

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章