头文件
#include "InsScpi.h"
#include <QObject>
#include <QSerialPort>
class TestSerial : public QObject
{
Q_OBJECT
public:
explicit TestSerial(QObject *parent = nullptr);
//打开设备
bool openDevice(const QString &portName);
//关闭设备
void closeDevice();
//发送数据
bool write(const char* cmd, qint64 maxSize);
//-- 获取温度
//-- 返回字符串格式:
//-- "22.3408 22.7402 24.3184 24.6043"
QString getTemp(bool& ok, int msec = 500);
signals:
void sig_finishReadSerial(); //完成串口读取信号
private:
void init(); //初始化函数
private:
QSerialPort* m_serialPort = nullptr; //串口
QString m_portName = "COM1"; //串口号
//串口描述信息
using QtSP = QSerialPort;
QtSP::BaudRate m_baudRate = QtSP::Baud115200; //波特率
QtSP::DataBits m_dataBits = QtSP::Data8; //数据位长度
QtSP::Parity m_parity = QtSP::NoParity; //校验位
QtSP::StopBits m_stopBits = QtSP::OneStop; //停止位
};
实现
#include <QDebug>
#include <QEventLoop>
#include <QTimer>
TestSerial::TestSerial( QObject *parent)
: QObject{parent}
{
(void)init();
}
void TestSerial::init()
{
//[1] 实例化串口对象
if (!m_serialPort)
{
m_serialPort = new QSerialPort();
}
}
bool TestSerial::openDevice(const QString &portName)
{
//[1] 判断串口对象是否实例化
if (!m_serialPort)
{
qDebug() << "serial obj is null";
return false;
}
//[2] 判断串口是否已经打开
if (m_serialPort->isOpen())
{
qDebug() << "device is already open";
return false;
}
//[3] 设置串口信息
m_portName = portName;
m_serialPort->setPortName(m_portName);
m_serialPort->setBaudRate(m_baudRate, QSerialPort::AllDirections);
m_serialPort->setDataBits(m_dataBits);
m_serialPort->setParity(m_parity);
m_serialPort->setStopBits(m_stopBits);
m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
//[4] 打开串口
return m_serialPort->open(QIODevice::ReadWrite);
}
void TestSerial::closeDevice()
{
//[1] 判断串口对象是否实例化
if (!m_serialPort)
{
qDebug() << "serial obj is null";
return;
}
//[2] 关闭串口
m_serialPort->close();
}
bool TestSerial::write(const char *cmd, qint64 maxSize)
{
//[1] 判断串口对象是否实例化
if (!m_serialPort)
{
qDebug() << "serial obj is null";
return false;
}
//[2] 判断串口是否打开
if (!m_serialPort->isOpen())
{
qDebug() << "serial is not open";
return false;
}
//[3] 发送数据
if(maxSize != m_serialPort->write(cmd, maxSize))
{
qDebug() << "send serial data failed";
return false;
}
return true;
}
//-- 获取温度
//-- 返回字符串格式:
//-- "22.3408 22.7402 24.3184 24.6043"
QString TestSerial::getTemp(bool& ok, int msec)
{
static QString ret;
ret.clear();
if (!m_serialPort){
qDebug() << "serial obj is null";
return "";
}
QEventLoop loop;
QObject::connect(this, &TestSerial::sig_finishReadSerial, &loop, &QEventLoop::quit);
QTimer::singleShot(msec, this, [&]{ emit sig_finishReadSerial(); });
QByteArray cmdBa = "getTemp()";
m_serialPort->clear();
if(0 != cmdBa.size()) {
if(cmdBa.size() == m_serialPort->write(cmdBa)) ok = true;
else ok = false;
}
auto async = QObject::connect(m_serialPort, &QSerialPort::readyRead, [&]() {
auto rcvData = m_serialPort->readAll();
ret = QString::fromLatin1(rcvData);
emit sig_finishReadSerial();
});
loop.exec();
QObject::disconnect(async);
return ret;
}