其實串口通訊網上文章不少了,你們看看基本能搞定,我只遇到過一個較難解決的問題,就是如何發送16進制的數據,將相關代碼貼出來你們參考函數
//16進制轉換函數 static QByteArray QString2Hex(QString str) { QByteArray senddata; int hexdata,lowhexdata; int hexdatalen = 0; int len = str.length(); senddata.resize(len/2); char lstr,hstr; for(int i=0; i<len; ) { hstr=str[i].toAscii(); if(hstr == ' ') { i++; continue; } i++; if(i >= len) break; lstr = str[i].toAscii(); hexdata = ConvertHexChar(hstr); lowhexdata = ConvertHexChar(lstr); if((hexdata == 16) || (lowhexdata == 16)) break; else hexdata = hexdata*16+lowhexdata; i++; senddata[hexdatalen] = (char)hexdata; hexdatalen++; } senddata.resize(hexdatalen); return senddata; } static char ConvertHexChar(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); }
注:「.toAscii()」在Qt5中要改成「toLatin1()」ui
上面是轉換函數,寫入的時候像下面這樣寫就好了spa
QByteArray senddata = Widget::QString2Hex(ui->lineEdit->text()); //轉換爲16進制 com->write(senddata);