遇到的坑
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.使用串口方法(将run函数当作槽函数,run函数里面运行的是另外一个线程,其他还是在主线程中)
//在主线程中新QThread
test_Thread = new QThread;
start_serialportthread = new serialportthread();
start_serialportthread->moveToThread(test_Thread);
test_Thread->start(); //开启串口线程
connect(this,SIGNAL(signal_openserialportThread()),start_serialportthread,SLOT(run()));
emit signal_openserialportThread();
//在串口线程中.h
private slots:
void run();
6.connect函数最后一个参数问题。信号与槽的连接方式问题。
信号与槽的连接方式 有如下几种
- Qt:: DirectConnection (立即调用)
- Qt::QueuedConnection (异步调用)
- Qt::BlockingQueuedConnection (同步调用)
- Qt: :AutoConnection (默认连接)
- Qt:: UniqueConnection (单一连接)
详细参见:https://blog.csdn.net/qq_39654127/article/details/81988281