串口初始化:MSComm1.CommPort = 1
MSComm1.SThreshold = 1
MSComm1.Settings = 9600,N,8,1
MSComm1.InBufferSize = 1024
MSComm1.OutBufferSize = 1024
MSComm1.InputMode = comInputModeBinary
打开串口并定时发送数据命令:Private Sub Timer1_Timer()
Dim bytearray(0 To 7) As Byte
bytearray(0) = &H1
bytearray(1) = &H3
bytearray(2) = &H0
bytearray(3) = &H2
bytearray(4) = &H0
bytearray(5) = &H8
bytearray(6) = &HE5
bytearray(7) = &HCC
MSComm1.InputLen = 21
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.RThreshold = 1
MSComm1.PortOpen = True
If MSComm1.PortOpen = True Then
MSComm1.Output = bytearray
End If
End Sub
接受数据:Private Sub MSComm1_OnComm()
Do
DoEvents
Loop Until MSComm1.InBufferCount = 21
Dim dataread() As Byte
Dim tempdata As Variant
Dim str As String
If MSComm1.CommEvent = comEvReceive Then
tempdata = MSComm1.Input
ReDim dataread(UBound(tempdata)) As Byte
For i = 0 To UBound(tempdata)
dataread(i) = tempdata(i)
End Sub
同理利用以上程序框图和通信协议可以完成下图的所有功能: