其實串口通信網上文章很多了,大家看看基本能搞定,我只遇到過一個較難解決的問題,就是如何發送16進制的數據,將相關代碼貼出來大家參考
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
//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()”
上面是轉換函數,寫入的時候像下面這樣寫就行了
1
2
|
QByteArray senddata = Widget::QString2Hex(ui->lineEdit->text()); //轉換爲16進制 com->write(senddata);
|