(1) 控件参数的初始化。
初始化程序如下:
MSComm.ComPort = 2 使用串口Com2
MSComm.Settings = "9600, E, 7, 2" 波特率9600,偶校验,7位数据位,
2位停止位
MSComm.PortOpen = True 打开通信端口,准备通信
(2) 计算校验码FCS,计算FCS的VB自定义函数如下:
Function FCS(ByVal InputStr As String) As String
Dim Slen, i, Xorresult As Integer
Dim Tempfes As String
Slen = Len(InputStr) 求输入字符串长度
Xorresult = 0
For i = 1 To Slen
Xorresult = Xorresult Xor Asc(Mid$(InputStr, i, 1))
按位异或
Next i
Tempfes = Hex$(Xorresult) 转化为16进制
If Len(Tempfes) = 1 Then Tempfes = "0" + Tempfes
FCS = Tempfes
End Function
(3) 计算机与PLC通信程序。
主要是一个自定义函数?
Function ReadData(ByVal InputStr As String, ByVal Num As Integer) As String
Dim OutputStr As String
Dim InString As String
Dim ReturnStr As String
Dim EndString As String
Dim FCSString As String
Dim ReturnFCSString As String
MSComm.InBufferCount = 0
OutputStr = InputStr + FCS(InputStr) + "*" 给出命令帧
MSComm.Output = OutputStr + Chr$(13) 向PLC传送命令帧
Do
DoEvents
Loop While MSComm.InBufferCount < 15
InString = MSComm.Input 获取PLC的响应帧
结束码判断
EndString = Mid$(InString)
Len(InString)
Num( 5, 2)
If EndString = "13" Then
ReadData = "Error"
Exit Function
ElseIf EndString = "14" Then
ReadData = "Error"
Exit Function
ElseIf EndString = "15" Then
ReadData = "Error"
Exit Function
ElseIf EndString = "18" Then
ReadData = "Error"
Exit Function
ElseIf EndString = "A3" Then
ReadData = "Error"
Exit Function
ElseIf EndString = "A8" Then
ReadData = "Error"
Exit Function
End If
响应帧校验
EndString = Mid$(InString, 1, Len(InString) - 4)
ReturnFCSString = Mid$(InString, Len(InString) - 3, 2)
FCSString = FCS(EndString)
If FCSString <> ReturnFCSString Then
ReadData = "Error"
Exit Function
End If
ReturnStr = Mid$(InString)
Len(InString) - Num - 3, Num)
ReadData = ReturnStr
End Function
其中有明显的3局是错误的,但是我对VB不太懂,我注释掉了,帮忙给我修改一下。
|