dim a1 as variant '定义a1为全局变量
Private Sub cmdSend_Click()
Dim bytData(0) As Byte
dim bytData(0) As Byte
dim bytData2 As variant
bytData(0) = &HF0
bytData1(0)=&HF
Call SendData(bytData)
call SendData1(bytData1)
bytData2 = a1
call SendData2(bytData2)
End Sub
Public Function SendData2(ByRef bytData2 As variant) As Long
text4.text = a1
On Error Resume Next
MSComm1.InBufferCount = 0 '清空接收缓冲区
MSComm1.Output = bytData2 '发送数据
Do
DoEvents
Loop Until MSComm1.OutBufferCount = 0 '等待,直到数据发送完毕
MSComm1.OutBufferCount = 0 '清空发送缓冲区
End Function
Public Function SendData1(ByRef bytData1() As Byte) As Long
On Error Resume Next
MSComm1.InBufferCount = 0 '清空接收缓冲区
MSComm1.Output = bytData 1'发送数据
Do
DoEvents
Loop Until MSComm1.OutBufferCount = 0 '等待,直到数据发送完毕
MSComm1.OutBufferCount = 0 '清空发送缓冲区
End Function
Public Function SendData(ByRef bytData() As Byte) As Long
On Error Resume Next
MSComm1.InBufferCount = 0 '清空接收缓冲区
MSComm1.Output = bytData '发送数据
Do
DoEvents
Loop Until MSComm1.OutBufferCount = 0 '等待,直到数据发送完毕
MSComm1.OutBufferCount = 0 '清空发送缓冲区
End Function
Private Sub Form_Load()
MSComm1.CommPort = 1 'COM端口
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 1 '产生MSComm事件
MSComm1.PortOpen = True '打开端口
Text3 = ""
End Sub
Private Sub MSComm1_OnComm()
On Error Resume Next
Dim BytReceived() As Byte
Dim strBuff As String
Dim strData As String
Dim i As Integer
Dim x As Integer
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
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
Text3 = Text3 + strData
If Left(strData, 2) = "F0" And Len(strData) = 4 Then
Text1.Text = strData
text2.text = right(strData,2)
a1 = text2.text
Call DataClear
End If
End Select
End Sub
Public Sub DataClear()
MSComm1.OutBufferCount = 0 '清空发送缓冲区
MSComm1.InBufferCount = 0
Text3 = ""
End Sub