使用qt Qserial 完成读
部分代码如下:
serial = new QSerialPort(this); //创建QSerialPort类
connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error), this, &SerialManager::handleError); //连接槽,串口出现问题连接到错误处理函数
connect(serial, &QSerialPort::readyRead, this, &SerialManager::readData); //将串口接到数据连接到自定义的接收数据函数
bool SerialManager::openSerialPort(QString portName , int BaudRate)
{
closeSerialPort();
serial->setPortName(portName);
serial->setBaudRate(BaudRate);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
//用可读写的方式打开串口
if (serial->open(QIODevice::ReadWrite))
{
qDebug() << "open success";
}
else
{
qDebug() << "open failed";
return false;
}
return true;
}
void SerialManager::readData()
{
QString tmpStr = serial->readAll();
tmpStr = tmpStr.trimmed().replace(" ","");
if(strBuffer.length() < SerialMsgMaxLength)
{
strBuffer+=tmpStr;
if(strBuffer.length() == SerialMsgMaxLength)
{
emit SgnRecvedMsg(strBuffer);
strBuffer.clear();
}
else if(strBuffer.length() > SerialMsgMaxLength)
{
strBuffer.clear();
}
}
}