QT 串列埠收發
阿新 • • 發佈:2018-12-31
myserial.c #include "myserial.h" MySerial::MySerial(QString com) { mCom = com; sendAck = 0; UartRxActive = false; serialInit(); } void MySerial::serialInit() { connect(this,SIGNAL(readyRead()),this,SLOT(serialRead())); //連線槽 //獲取計算機上所有串列埠並新增到comboBox中 QList<QSerialPortInfo> infos = QSerialPortInfo::availablePorts(); if(infos.isEmpty()) { this->close(); errorText = "未找到串列埠"; //emit msendError("未找到串列埠"); return; }else{ foreach (QSerialPortInfo info, infos) { if(mCom == info.portName()) { this->setPortName(mCom); if(this->open(QIODevice::ReadWrite)) //讀寫開啟 { this->setBaudRate(QSerialPort::Baud115200); //波特率 this->setDataBits(QSerialPort::Data8); //資料位 this->setParity(QSerialPort::NoParity); //無奇偶校驗 this->setStopBits(QSerialPort::OneStop); //無停止位 this->setFlowControl(QSerialPort::NoFlowControl); //無控制 }else{ this->close(); errorText = "無法開啟串列埠"; // emit msendError("無法開啟串列埠"); } return; } } } } bool MySerial::SendWaitAck(QByteArray data, int waitTime) { int retryCnt = 0; errorText.clear(); do{ QCoreApplication::processEvents(QEventLoop::AllEvents,100); if((retryCnt)== 0){//不允許重發 if((retryCnt % 500)== 0) sendAck = 0; UartSendData(this, data); } delay_ms(1); retryCnt++; }while((sendAck == 0) && (retryCnt < waitTime)); if(sendAck == 0) errorText = "檢未響應"; else if(sendAck == -1) errorText = "ACK異常"; return sendAck; } bool MySerial::Send(QByteArray data) { UartSendData(this, data); return true; } //強烈要求兩個資料傳送之間有10ms間隔,之間過短導致接收到的ACK會連在一起不好處理 //原因不明 void MySerial::serialRead(void) { int index; QByteArray data = this->readAll(); if(data.count(0x7E) == 2){ int length = Data_Decode(data.data(),(u16)data.size()); data.resize(length); if(data.at(0) == 'U') { if(data.at(1) == 0x6) sendAck = 1; else if(data.at(1) == 0x15) sendAck = -1; } }else{//斷包處理,不能避免斷包 index = data.indexOf(0x7E); if(UartRxActive){ if(index == -1) buffRecv.append(data); else{ buffRecv.append(data.mid(0, index + 1)); UartRxActive = false; int length = Data_Decode(buffRecv.data(),(u16)buffRecv.size()); buffRecv.resize(length); if(buffRecv.at(0) == 'U') { if(buffRecv.at(1) == 0x6) sendAck = 1; else if(buffRecv.at(1) == 0x15) sendAck = -1; } buffRecv.clear(); } }else if(index != -1){ buffRecv.append(data.mid(index)); UartRxActive = true; } } }
myserial.h
#ifndefMYSERIAL_H
#defineMYSERIAL_H
#include<QSerialPort>
#include<QSerialPortInfo>
#include<class.h>
classMySerial:publicQSerialPort
{
Q_OBJECT
public:
MySerial(QStringcom);
boolSendWaitAck(QByteArraydata,intwaitTime);
boolSend(QByteArraydata);
intsendAck;
QStringerrorText;
privateslots:
voidserialRead(void);
private:
voidserialInit();
private:
QStringmCom;
QByteArraybuffRecv;
boolUartRxActive;
//QSerialPort*serial;//串列埠例項
};
#endif//MYSERIAL_H