本文主要是介绍QT实现串口的十六进制发送,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
void
MainWindow
::on_pushBUtton_clicked
()
//发送数据
{
QString strTXData;
QByteArray hexdata;
// strTXData = ui->lineEdit->text().toAscii();//txTextEdit
strTXData = ui->txTextEdit->toPlainText().toAscii();
if(ui->txHexcheckBox->isChecked()==true)
{
QByteArray temp;
QString strHex;
//count1=stringToHex(strTXData,hexdata);
stringToHex(strTXData,hexdata);
myCom->write(hexdata);
temp =hexdata;
QDataStream out(&temp,QIODevice::ReadWrite);//将字节数组读入
while(!out.atEnd()) {
qint8 outChar = 0;
out >> outChar;//每字节填充一次,直到结束
QString str = QString("%1").arg(outChar&0xFF, 2, 16, QLatin1Char('0'));//十六进制的转换
count1++;
strHex += str;
}
ui->TxlineEdit->setText(QString::number(count1));
}
……………………………………………………
int MainWindow::stringToHex(QString str,QByteArray &senddata){
int hexdata,lowhexdata;int hexdatalen = 0;int len = str.length();senddata.resize(len/2);//char lstr,hstr;str[len]=' ';for(int i=0; i<len; ){hstr=str[i].toAscii();//if(hstr == 0x0a)// continue;i++;lstr=str[i].toAscii();if(lstr == ' '){lstr=hstr;hstr='0';i++;}else{i++;if(str[i]!=' '){}else{i++;}}if(i >= len+2)break;hexdata = ConverToHexChar(hstr);lowhexdata = ConverToHexChar(lstr);if((hexdata == 16) || (lowhexdata == 16))break;elsehexdata = hexdata*16+lowhexdata;senddata[hexdatalen] = (char)hexdata;hexdatalen++;}senddata.resize(hexdatalen);return hexdatalen;}
char MainWindow::ConverToHexChar(char ch){
if((ch >= '0') && (ch <= '9'))return ch-0x30;else if((ch >= 'A') && (ch <= 'F'))return ch-'A'+10;else if((ch >= 'a') && (ch <= 'f'))return ch-'a'+10;else return (-1);}
这篇关于QT实现串口的十六进制发送的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!