VB MSCOMM串口通讯
展开全部
看看 这个
当设置MSComm 控件的InputMode 属性为comInputModeBinary时,串口是按返回一数据组的二进制数据(Byte)字节的数组,但MSComm1.Input可赋值给一个String变量strBuff,在转赋值给Byte数组BytReceived(),而不会出现歧义,其接收代码如下:
Option Explicit
Dim strData As String
Private Sub Form_Load()
Text1 = ""
Text2 = ""
MSComm1.CommPort = 1
MSComm1.InputMode = comInputModeBinary '数据通过 Input 属性以文本形式取回。
MSComm1.RThreshold = 1
MSComm1.Settings = "9600,N,8,1"
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm() '接收数据
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 = ""
'数据处理代码
End Select
End Sub
祝你顺利
当设置MSComm 控件的InputMode 属性为comInputModeBinary时,串口是按返回一数据组的二进制数据(Byte)字节的数组,但MSComm1.Input可赋值给一个String变量strBuff,在转赋值给Byte数组BytReceived(),而不会出现歧义,其接收代码如下:
Option Explicit
Dim strData As String
Private Sub Form_Load()
Text1 = ""
Text2 = ""
MSComm1.CommPort = 1
MSComm1.InputMode = comInputModeBinary '数据通过 Input 属性以文本形式取回。
MSComm1.RThreshold = 1
MSComm1.Settings = "9600,N,8,1"
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm() '接收数据
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 = ""
'数据处理代码
End Select
End Sub
祝你顺利
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询