Dim PlcBack As String
Private Sub Form_Load()
MSComm1.CommPort = 4 '端口号
MSComm1.Settings = "9600,n,8,1" '通讯格式 要与PLC设置对应
MSComm1.InputLen = 0 '将接收缓冲区内容全部读回来
MSComm1.OutBufferCount = 0
'*设置并返回发送缓冲区的字节数,设为0时清空发送缓冲区
MSComm1.InBufferCount = 0
'*设置并返回接收缓冲区的字节数,设为0时清空接收缓冲区
MSComm1.InputMode = comInputModeBinary
'二进制接收
MSComm1.RThreshold = 1
'*产生ON_COMMM事件的字符数
MSComm1.PortOpen = True
'*打开串口
End Sub
Private Sub Form_Unload(Cancel As Integer)
End
End Sub
Private Sub MSComm1_OnComm()
Dim getData() As Byte '*读取接收缓冲区变量
Dim getData_len As Long '*判断读取长度
Dim j As Integer
Dim ErrorPlc As String
Dim DataD As String
If MSComm1.CommEvent = comEvReceive Then
'*CommEvent的属性返回的值为comEvReceive时是发生了接收事件.
getData = MSComm1.Input
'*读取接收缓冲区内容
getData_len = UBound(getData)
'返回一个 Long 型数据,其值为指定的数维组可用的最大下标
For j = 0 To getData_len '*将读取的字节变换为字符
PlcBack = PlcBack & Right("00" + Hex(getData(j)), 2)
Next j
If InStr(PlcBack, "23") = 0 Then
ErrorPlc = "没有接收到起始符"
Else
If InStr(PlcBack, "26") = 0 Then
ErrorPlc = "没有接收到结束符"
Else
DataD = Mid(PlcBack, InStr(PlcBack, "23") + 2, 2) '*最后一个2是读取数据的字节数
End If
End If
Text1.Text = DataD
Text2.Text = Text1.Text
End If
End Sub