|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- //读取串口数据并处理
- QByteArray temp=serial->readAll();
- QDataStream out(&temp,QIODevice::ReadWrite);
- while(!out.atEnd())
- {
- qint8 outChar=0;
- out>>outChar;
- QString byte=QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));
- byte=byte.toUpper();
-
- //协议解析状态机
- if(state_machine==0)
- {
- //判断第一个帧头
- if(byte==0xaa)
- {
- state_machine=1;
- }
- else
- {
- //状态机复位
- state_machine=0;
- }
- }
- else if(state_machine==1)
- {
- //判断第二个帧头
- if(byte==0xbb)
- {
- state_machine=2;
- }
- else
- {
- state_machine=0;
- }
- }
-
- //判断接收长度
- else if(state_machine==2)
- {
- buffer+=byte;
- bufferdatalen+=byte;
- //接收数据计数器
- lencnt=0;
- //接收数据长度
- datalen=bufferdatalen.toInt(&ok,16);
- }
-
- //判断接收的地址
- else if(state_machine==3)
- {
- if(byte==0x01)
- {
- state_machine=4;
- }
- else
- {
- state_machine=0;
- }
- }
- //协议数据处理
- else if(state_machine==4||state_machine==5||state_machine==6||state_machine==7)
- {
- //保存数据
- frameData+=byte;
- if(lencnt==datalen)
- {
- state_machine=8;
- }
- else
- {
- state_machine=7;
- ++lencnt;
- }
- }
- //进行校验
- else if(state_machine==8)
- {
- TxNum=0;
- if(buffer.isEmpty())
- {
- return;
- }
- //QByteArray temp;
- //获取buffer数据
- temp=QByteArray::fromHex(buffer.toLatin1().data());
- //将数组读入
- QDataStream out(&temp,QIODevice::ReadWrite);
- while(!out.atEnd())
- {
- qint8 outchar=0;
- //每一字节进行填充,直到结束
- out>>outchar;
- SendBuf[TxNum]=(uint8_t)(outchar &0xff);
- TxNum++;
- }
- //求帧头以外所有数据的校验和
- checkSum=(uint8_t)(Sum_Calculate(SendBuf,TxNum));
- QString strSum=QString("%1").arg(checkSum&0xFF,2,16,QLatin1Char('0'));
- strSum=strSum.toUpper();
- byte=byte.toUpper();
- if(byte==strSum)
- {
- state_machine=9;
- }
- else
- {
- state_machine=0;
- }
- }
- //判断是否接收到帧尾结束
- else if(state_machine==9)
- {
- ....
- //校验函数
- uint8_t MainWindow::Sum_Calculate(uint8_t *puchMsg, uint16_t usDataLen)
- {
- uint8_t CRCValue=0;
- uint16_t i=0;
- for(i=0;i<usDataLen;i++)
- {
- CRCValue=puchMsg[i]^CRCValue;
- }
- return CRCValue;
- }
复制代码
我想基于Qt实现接收形如“0xaa 0xbb 0x长度 0x地址 0x数据 0x校验 0x55 0x66”这种格式的数据,不知道我上面写得代码哪里错了,请大家指教!!!
可以提供代码进行学习吗? |
|