VB与PLC通信程序(欧姆龙PLC)
分类:| 转自:原文地址被1人转藏+放进我的宝盒2010-9-2 21:45:46
VB与PLC通信程序(欧姆龙PLC)
关于VB的MSCOMM控件可参考相关资料。
通信程序摘要如下:
(1)初始化程序
mport=2 ’选择COM2
Mscomm1.Settings=”9600,N,8,2”’设置通信参数
Mscomm1.Inputlen=0 ’读入接收缓冲区全部字符
Mscomm1.OutbufferSize=256 ’设置发送缓冲区大小
Mscomm1.InbufferSize=512 ’设置接收缓冲区大小
Mscomm1.PortOpen=True ’打开COM2
(2)发送命令程序
比如读取节点号03的PLC中IR000到IR009的内容,并放到tag1字符串变量中,此时有:
Dim Command, node, begin, number as string
Dim Answerlen as integer
node=”03”’节点号
Command=”RR”’命令为读IR区
begin=”0000”’从IR000开始
number=10 ’读取长度
Answerlen=51 ’计算接收字符串长度
进行命令发送和接收应答处理:
Dim FCS, I as integer
Dim s ,f as string
s=”@”+node+Commad+begin+number
FCS=0
For i=1 to Len(s)
FCS=FCS xor Asc(Mid$(s,i,1) ) ’帧校验码FCS
Next i
f=Hex$(FCS)
If Len(f)=1 Then f=”0”+f
Commfrm.MSComm1.Output=s + f + ”*”+ CHR$(13) ’命令帧发送
Do
Dummy=DoEvents()
Loop Untill Commfrm.MSComm1.InbufferCount >= Answerlen ’等待应答帧
Do tag1= Commfrm.MSComm1.Input
Loop Untill Commfrm.MSComm1.InbufferCount=0 ’读完应答帧
上述程序具有相当的通用性,对于其它设备不同的只是各自的数据帧格式,因而只需做相应少量修改即可。