1. 初始化QSerialPort类
//setting.h 这是样例对应的头文件
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
class _setting : public QWidget
{
Q_OBJECT
public:
_setting(QWidget* parent = Q_NULLPTR);
~_setting();
QSerialPort* testPort = nullptr;
//QSerialPort* testPort =new QSerialPort
QString testPort_name;
QByteArray testData;
private:
Ui::_setting ui;
};
2. 设置参数、编写指令、传回数据
//setting.cpp 样例对应的cpp文件
void _setting::establish_SensorConnection()
{
delete testPort;
testPort = new QSerialPort;
//1.找串口名字
foreach(const QSerialPortInfo & qspinfo, QSerialPortInfo::availablePorts())
{
if (qspinfo.portName() != "COM1" && qspinfo.portName() != "COM2")
{
testPort_name = qspinfo.portName();
}
}
//2.判空
if (testPort_name.isEmpty())
{
if (!MaskWin::GetInstance()->isHidden())
{
MaskWin::GetInstance()->hide();
}
tooltip->load_tips("请检查USB线接口");
this->hide();
return;
}
//3.设置参数
testPort->setPortName(testPort_name);
testPort->setBaudRate(115200);
testPort->setDataBits(QSerialPort::Data8);
testPort->setParity(QSerialPort::NoParity);
testPort->setStopBits(QSerialPort::OneStop);
if (testPort->open(QIODevice::ReadWrite))
{
//4.编写指令参数
QByteArray command;
command[0] = 0xAA;
command[1] = 0x05;
command[2] = 0x00;
command[3] = 0x00;
command[4] = 0x00;
command[5] = 0x00;
command[6] = 0x00;
command[7] = 0xFF;
testData = testPort->readAll();
testPort->write(command);
QTime dieTime = QTime::currentTime().addMSecs(500);//延时500毫秒
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
//5.读取传感器传回数据
testData = testPort->readAll();
}
else
{
qDebug() << "Error:" << testPort->errorString();
testPort_name = nullptr;
}
}
以上大概是使用QSerialPort类的基础框架。