qt串口十六进制发送和接收

来源:互联网 发布:梦里花落知多少的小说 编辑:程序博客网 时间:2024/05/19 19:40

转载自http://www.linuxidc.com/Linux/2011-09/42421.htm 和http://blog.csdn.net/xhao014/article/details/6663738

最近做一个东西,它的指令是以十六进制发送的,而我又要以串口形式发送,这不,就需要这方面的资料(在这个网站http://www.gjwtech.com/vcandc/scommassistantcode02.htm,得到参考,仿照写了一下,还真成了,当然,也有群里的高手指导下)。

OK,下面就来具体说怎么实现的。

我的界面是这样的,点击一次,然后读取它返回的信息。

参考上面网站的内容,自己稍微修改下,程序如下:

 

[cpp] view plaincopy
  1. void Widget::String2Hex(QString str, QByteArray &senddata)  
  2. {  
  3.     int hexdata,lowhexdata;  
  4.     int hexdatalen = 0;  
  5.     int len = str.length();  
  6.     senddata.resize(len/2);  
  7.     char lstr,hstr;  
  8.     for(int i=0; i<len; )  
  9.     {  
  10.         //char lstr,  
  11.         hstr=str[i].toAscii();  
  12.         if(hstr == ' ')  
  13.         {  
  14.             i++;  
  15.             continue;  
  16.         }  
  17.         i++;  
  18.         if(i >= len)  
  19.             break;  
  20.         lstr = str[i].toAscii();  
  21.         hexdata = ConvertHexChar(hstr);  
  22.         lowhexdata = ConvertHexChar(lstr);  
  23.         if((hexdata == 16) || (lowhexdata == 16))  
  24.             break;  
  25.         else  
  26.             hexdata = hexdata*16+lowhexdata;  
  27.         i++;  
  28.         senddata[hexdatalen] = (char)hexdata;  
  29.         hexdatalen++;  
  30.     }  
  31.     senddata.resize(hexdatalen);  
  32. }  


 

[cpp] view plaincopy
  1. char Widget::ConvertHexChar(char ch)  
  2. {  
  3.     if((ch >= '0') && (ch <= '9'))  
  4.         return ch-0x30;  
  5.     else if((ch >= 'A') && (ch <= 'F'))  
  6.         return ch-'A'+10;  
  7.     else if((ch >= 'a') && (ch <= 'f'))  
  8.         return ch-'a'+10;  
  9.     else return (-1);  
  10. }  


两个主要函数改写完毕,下面就是一般的串口操作了。就不在啰嗦了。

值得注意的是,hstr=str[i].toAscii();和 lstr = str[i].toAscii();   不加toAscii的话,就会报错。这个就是群里高手提点的,当然,他没直接给出要加toAscii,而是帮我解释了下错误原因,这个是比较重要的。


//读取串口
void MySerial::readMyCom()
{
    QByteArray temp;
    if(myCom->bytesAvailable() >= 8)
    {
        temp = myCom->readAll(); //读串口缓冲区数据  
    }
    QDataStream out(&temp,QIODevice::ReadWrite);    //将字节数组读入
    while(!out.atEnd())
    {
        qint8 outChar = 0;
        out>>outChar;   //每字节填充一次,直到结束
        QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));
        //十六进制的转换
        recBrowser->insertPlainText(str);
    }
    recBrowser->insertPlainText(tr("\n"));
}

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2011-09/42421.htm