最近在使用串口读一些数据,但是总会出现些发、送之间的冲突问题,为了弄清楚问题的所在,于是产生了想法,做了一个日志保存。
- void Widget::SaveLogTxt(QString dat )
- {
- QDateTime currenttime = QDateTime::currentDateTime();
- QString strDate = currenttime.toString("yyyy/MM/dd");
- QString strTime = currenttime.toString("hh:mm:ss.zzz");
- QString path = QCoreApplication::applicationDirPath();
- QString strPath = "C://Users//user//Desktop//RS485/log.txt";
- qDebug()<<strPath;
- QFile file(strPath);
- bool isOK = file.open(QIODevice::WriteOnly|QIODevice::Append);
- if(isOK){
- QTextStream stream(&file);
- stream<<strDate<<strTime<<"\r\n";
- stream<<dat<<"\r\n";
- }
- qDebug()<<dat;
- file.close();
- }
- void Widget::getData()
- {
- // QByteArray rxData;
- QString strTemp;
- uint8_t index = 0;
- QByteArray datTemp ,temp;
- strLog = "";
- strLog += "收到的数据";
- strLog += "\r\n";
- rxData = serial_device->readAll();
- for(int i = 0 ; i < rxData.size() ; i++){
- //解析到帧头
- if(0x55 == rxData[i] && 0xaa == (uint8_t)rxData[i+1]){
- index = i;
- qDebug()<<"index"<<index;
- //拷贝剩余数据
- for(int j = 0 ; j < rxData.size() - index; j++){
- datTemp[j]= rxData[index+j];
- }
- qDebug()<<"datTempSize"<<datTemp.size()<<"datTemp"<<datTemp.toHex(':');
- SaveLogTxt("解析到指令数据\r\n"+datTemp.toHex(':'));
- writedata();
- }else{
- index = 0;
- datTemp.clear();
- }
- }
- for(int i = 0 ; i < rxData.size() ; i++){
- strTemp.sprintf("%02x",(uint8_t)rxData[i]);
- strLog += strTemp + " ";
- }
- rxData.clear();
- SaveLogTxt(strLog);
- }
- void Widget::writedata()
- {
- QString strTemp;
- strLog = "";
- strLog += "发送的数据";
- strLog += "\r\n";
- uint8_t TxData[6]={0x55 ,0xaa, 0x03, 0x82, 0x02};//获取市电状态
- TxData[5] = (TxData[0] + TxData[1] +TxData[2] + TxData[3] + TxData[4])&0xff;
- for(int i = 0 ; i < 6 ; i++){
- strTemp.sprintf("%02x",TxData[i]);
- strLog += strTemp + " ";
- }
- serial_device->write((const char*)TxData , 6);
- SaveLogTxt(strLog);
- }
作者: E_ARM, 来源:面包板社区
链接: https://mbb.eet-china.com/blog/uid-me-3989713.html
版权声明:本文为博主原创,未经本人允许,禁止转载!
文章评论(0条评论)
登录后参与讨论