MSComm 控件的Input 屬性及InputMode 屬性探究
最近對(duì)MSComm 控件的Input 屬性研究得出一些觀點(diǎn),提供給各位關(guān)心串口通信的愛好者。
當(dāng)設(shè)置MSComm 控件的InputMode 屬性為comInputModeText時(shí),串口是按返回接收到的ASCII碼在MSComm 控件轉(zhuǎn)換成Unicode碼。
以下代碼可揭示上述結(jié)論:
Option Explicit
Dim strData As Variant
Private Sub Command1_Click()
Text2 = ""
End Sub
Private Sub Form_Load()
Text1 = ""
Text2 = ""
MSComm1.CommPort = 1
MSComm1.InputMode = comInputModeText '數(shù)據(jù)通過 Input 屬性以文本形式取回。
MSComm1.RThreshold = 1
MSComm1.Settings = "9600,N,8,1"
MSComm1.PortOpen = True
MSComm1.InputLen = 1
End Sub
Private Sub MsComm1_OnComm() '接收數(shù)據(jù)
Dim BytReceived() As Byte
Dim strBuff As String
Select Case MSComm1.CommEvent
Case 2
Text1 = ""
Text3 = MSComm1.InBufferCount '接收緩沖區(qū)的字節(jié)數(shù)
strBuff = MSComm1.Input '
BytReceived() = strBuff '
Dim i As Integer
For i = 0 To UBound(BytReceived)
If Len(Hex(BytReceived(i))) = 1 Then
strData = strData & "0" & Hex(BytReceived(i))
Else
strData = strData & Hex(BytReceived(i))
End If
Next
'數(shù)據(jù)處理代碼
Dim sj As String
sj = Right(strData, 2) & Left(strData, 2)
Text1 = strData
Text2 = Text2 & ChrW(Val("&H" & sj))
strData = ""
End Select
End Sub
注意上述代碼中設(shè)置MSComm 控件的InputMode 屬性為comInputModeText,而接收是按2進(jìn)制Byte字節(jié)的數(shù)組取出。
用一串口調(diào)試程序發(fā)送文本字節(jié),單個(gè)漢字或單個(gè)ASCII字符(英文字母或0-9數(shù)字),你會(huì)發(fā)現(xiàn),接收到漢字時(shí)MSComm1.InBufferCount值為2,接收A-Z(a-z,0-9)時(shí)MSComm1.InBufferCount值為1。同時(shí)Text2中顯示分別是調(diào)試串口程序發(fā)送的單個(gè)漢字或單個(gè)ASCII字符(英文字母或0-9數(shù)字)。
當(dāng)設(shè)置MSComm 控件的InputMode 屬性為comInputModeBinary時(shí),串口是按返回一數(shù)據(jù)組的二進(jìn)制數(shù)據(jù)(Byte)字節(jié)的數(shù)組,但MSComm1.Input可賦值給一個(gè)String變量strBuff,在轉(zhuǎn)賦值給Byte數(shù)組BytReceived(),而不會(huì)出現(xiàn)歧義,其接收代碼如下:
Option Explicit
Dim strData As String
Private Sub Form_Load()
Text1 = ""
Text2 = ""
MSComm1.CommPort = 1
MSComm1.InputMode = comInputModeBinary '數(shù)據(jù)通過 Input 屬性以文本形式取回。
MSComm1.RThreshold = 1
MSComm1.Settings = "9600,N,8,1"
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm() '接收數(shù)據(jù)
Dim BytReceived() As Byte
Dim strBuff As String
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
Text1 = ""
Text2 = ""
Text3 = MSComm1.InBufferCount
strBuff = MSComm1.Input
BytReceived() = strBuff
Dim i As Integer
For i = 0 To UBound(BytReceived)
If Len(Hex(BytReceived(i))) = 1 Then
strData = strData & "0" & Hex(BytReceived(i))
Else
strData = strData & Hex(BytReceived(i))
End If
Next
Dim sj As String
sj = strData
Text1 = sj
Text2 = Chr(Val("&H" & sj))
strData = ""
'數(shù)據(jù)處理代碼
End Select
End Sub