#include "serialport.h" #include #include #include #include #include "protocol.h" using namespace std; const QString conSPName = "COM3"; const QString conPid = "7523"; const QString conVid = "1a86"; SerialPort::SerialPort(QObject*parent) :QObject(parent) ,_sp(nullptr) { // init(); #if 1 // 1.初始化 _sp = new QSerialPort(); _sp->setPortName(conSPName); if(_sp == nullptr){ qDebug()<<"sp is null."; exit(0); return; } // 3.设置 //设置波特率和读写方向 _sp->setBaudRate(QSerialPort::Baud115200, QSerialPort::AllDirections); _sp->setDataBits(QSerialPort::Data8); //数据位为8位 _sp->setFlowControl(QSerialPort::NoFlowControl);//无流控制 _sp->setParity(QSerialPort::NoParity); //无校验位 _sp->setStopBits(QSerialPort::OneStop); //一位停止位 //4.连接信号槽 connect(_sp,&QSerialPort::readyRead, this,&SerialPort::slotReadData); // 2.打开串口 if(false == _sp->open(QIODevice::ReadWrite)){ qDebug()<<"open failed." <<_sp->error(); exit(0); } else{ qDebug()<<"open succ."; // 设置 DTR 信号为就绪状态(true 表示低电平) _sp->setDataTerminalReady(true); } //写数据定时器 // startTimer(500); #endif #if 0 sendCmd(e_zero); for(int i = 0; i < 9; i++){ sendCmd(e_back); } #endif } SerialPort *SerialPort::instance() { static SerialPort ins; return &ins; } SerialPort::~SerialPort() { if(_sp->isOpen()){ _sp->clear(); _sp->close(); } delete _sp; _sp=nullptr; } void SerialPort::timerEvent(QTimerEvent *event) { } void SerialPort::slotReadData() { QByteArray info = _sp->readAll(); // 将 QByteArray 转换为十六进制字符串 QString hexData = info.toHex(' '); // ' ' 作为分隔符,可选参数 qDebug() << "receive info (hex):" << hexData; } void SerialPort::init() { foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { #if 0 qDebug() << "Name : " << info.portName(); qDebug() << "Description : " << info.description(); qDebug() << "Manufacturer: " << info.manufacturer(); qDebug() << "Serial Number: " << info.serialNumber(); qDebug() << "System Location: " << info.systemLocation(); qDebug()<<"portName"<< info.portName(); qDebug() <write(out_char, hex_length); if(num == -1){ qDebug()<<"write failed."; }else{ qDebug()<<"write ok|num:"<(const_cast(&data[4])); qDebug()<<"run type:"<run_type; // qDebug()<<"run time:"<add_run_time; // qDebug()<<"sample temp:"<sample_temp; // 格式化输出 float 类型,保留两位小数 QString formattedRunTime = QString::number(serialPortData->add_run_time, 'f', 2); qDebug() << "run time:" << formattedRunTime; // 格式化输出 double 类型,保留三位小数 QString formattedSampleTemp = QString::number(serialPortData->sample_temp, 'f', 3); qDebug() << "sample temp:" << formattedSampleTemp; // 定义小端序的 4 字节数据 unsigned char bytesLittle[] = {0x23, 0x23, 0x01, 0x00}; // 调用函数进行转换 float result = 0.0f; std::memcpy(&result, bytesLittle, sizeof(float)); // float floatValue = bytesToFloatLittleEndian(bytesLittle); // 输出转换后的浮点数 std::cout << "小端序下的浮点数: " << floatValue << std::endl; }