7,785
社区成员




Option Explicit
Dim outputArray() As Byte
Dim inputArray(0 To 1023) As Byte
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub btnComm_Click()
ReDim outputArray(0 To 4) As Byte
outputArray(0) = &HD1
outputArray(1) = &H2
outputArray(2) = &H0
outputArray(3) = &H1
outputArray(4) = &H2A
mscP.Output = outputArray
End Sub
Private Sub Form_Load()
With mscP
.CommPort = 1 '定义通信端口号
.Settings = "9600,n,8,1" '定义通信的波特率、校验方式、数据位、停止位
.InputLen = 1 '定义每次在接收缓冲区中读取的字符数
.OutBufferSize = 1024 '定义发送缓冲区大小
.OutBufferCount = 0 '清空发送缓冲区
.InBufferCount = 0 '清空接收缓冲区
.InBufferSize = 1024 '定义接收缓冲区大小
.InputMode = comInputModeBinary '以十六进制进行通信
.RThreshold = 1 '接收到一个字符就触发OnComm时间
If Not .PortOpen Then .PortOpen = True '打开串口
End With
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If mscP.PortOpen Then mscP.PortOpen = False '关闭端口
End Sub
Private Sub mscP_OnComm()
Dim varInput As Variant
Dim intP As Integer
'当串口接收缓冲区收到数据时...
If mscP.CommEvent = 2 Then
mscP.RThreshold = 0 '屏蔽OnComm事件
Sleep 20 '停止20ms,以便串口数据完全返回
intP = 0
Do
varInput = Null
varInput = mscP.Input
If Not IsNull(varInput) Then inputArray(intP) = varInput(0)
intP = intP + 1
Loop Until mscP.InBufferCount <= 0
mscP.RThreshold = 1 '恢复OnComm事件的触发
End If
End Sub