帮忙看看这段通信代码

[复制链接]
查看2417 | 回复2 | 2006-5-16 17:47:00 | 显示全部楼层 |阅读模式

(1) 控件参数的初始化。

初始化程序如下:

MSComm.ComPort = 2 使用串口Com2

MSComm.Settings = "9600, E, 7, 2" 波特率9600,偶校验,7位数据位,

2位停止位

MSComm.PortOpen = True 打开通信端口,准备通信

(2) 计算校验码FCS,计算FCSVB自定义函数如下:

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不太懂,我注释掉了,帮忙给我修改一下。

gongkonglxw | 2006-5-16 18:02:00 | 显示全部楼层

最好放到VB中跑一下,一眼就看出来了

gongkonglxw | 2006-5-16 18:02:00 | 显示全部楼层
您需要登录后才可以回帖 登录 | 注册哦

本版积分规则