pro

QT+= serialport

serialPort_.h

#ifndef SERIALPORT__H
#define SERIALPORT__H

#include <QObject>
#include <QSerialPort>
#include <QSerialPortInfo>



class serialPort_:public QObject
{
Q_OBJECT

public:
serialPort_(QObject*o=0);

/**
* @projectName testMyClass
* @brief 打开串口 根据名字 波特率 数据位 校验位 停止位 流控制
* 返回打开成功还是失败
* @author SMY
* @date 2019-03-21
*/

bool openPort(QString portName,qint32 baudRate,QSerialPort::DataBits dataBits,
QSerialPort::Parity parity,QSerialPort::StopBits stopBits,
QSerialPort::FlowControl flowControl);

/**
* @projectName testMyClass
* @brief 是否打开串口
* @author SMY
* @date 2019-03-21
*/
bool isOpen()const{
return m_port->isOpen();
}

/**
* @projectName testMyClass
* @brief 关闭串口
* @author SMY
* @date 2019-03-21
*/
void closePort(){
m_port->clear();
m_port->close();
}
/**
* @projectName testMyClass
* @brief 获取可用的串口名字
* @author SMY
* @date 2019-03-21
*/
QStringList getAvailablePortNameList()const
{
QStringList portName;
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
portName<<info.portName();

}
return portName;
}

/**
* @projectName testMyClass
* @brief 串口写数据
* @author SMY
* @date 2019-03-21
*/
void write(QString str);
void write(const char *data, qint64 len);

/**
* @projectName testMyClass
* @brief QByteArray 转换为 QString
* @author SMY
* @date 2019-03-21
*/
QString ByteArrayToHexString(QByteArray data);

signals:
/**
* @projectName testMyClass
* @brief 串口读取到数据的信号
* @author SMY
* @date 2019-03-21
*/

void readyRead(QByteArray data);

private:
QSerialPort *m_port;

void readyRead_slot();



};

#endif // SERIALPORT__H

serialPort_.cpp

#include "serialport_.h"

serialPort_::serialPort_(QObject *o)
{
m_port = new QSerialPort();


connect(m_port,&QSerialPort::readyRead,this,&serialPort_::readyRead_slot);

}

bool serialPort_::openPort(QString portName, qint32 baudRate,
QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
QSerialPort::StopBits stopBits, QSerialPort::FlowControl flowControl)
{

m_port->setPortName(portName);
m_port->setBaudRate(baudRate);
m_port->setDataBits(dataBits);
m_port->setParity(parity);
m_port->setStopBits(stopBits);
m_port->setFlowControl(flowControl);

if(m_port->open(QIODevice::ReadWrite))
{
return true;
}
else
return false;
}

void serialPort_::write(QString str)
{
m_port->write(str.toUtf8().data());
}

void serialPort_::write(const char *data, qint64 len)
{
m_port->write(data,len);
}

QString serialPort_::ByteArrayToHexString(QByteArray data)
{
QString ret(data.toHex().toUpper());
int len = ret.length()/2;
for(int i=1;i<len;i++)
{
ret.insert(2*i+i-1," ");
}

return ret;
}

void serialPort_::readyRead_slot()
{
QByteArray data = m_port->readAll();
emit readyRead(data);
}