在界面中用按钮控制y0的on/off及d100、d200数据的写与读;用shape组件做指示灯,指示y0的on/off状态;用winsock控件实现plc与vb的通信。 (1)实现功能的代码构成 (2)建立网络连接 private sub command1_click() winsock1.close winsock1.connect text1, 502 label2.caption = version: 1.0 : + format(now, mmm dd yyyy hh:nn:ss) command1.enabled = false command1.enabled = false text1.enabled = false end sub (2)、y0的on/off控制 private sub comd_send_click() on error goto errproc dim sendstr(14) as byte sendstr(0) = &h0 交换识别号高字节,通常为0 sendstr(1) = &h0 交换识别号低字节,通常为0 sendstr(2) = &h0 协议识别号高字节,为 0 sendstr(3) = &h0 协议识别号低字节,为 0 sendstr(4) = &h0 字节长度高字节 sendstr(5) = &h9 以下字节长度低字节 sendstr(6) = &hff 单元识别号,确省为 255 sendstr(7) = &h5 写一个线圈命令代码 sendstr(8) = &h0 写线圈的起始地址高字节 sendstr(9) = &h1写线圈的起始地址低字节 sendstr(10) = a =ff打开线圈,=00关闭线圈 sendstr(11) = &h0 dim astr as string dim i, j as integer for i = 0 to 11 astr = astr & chr(sendstr(i)) next winsock1.senddata astr exit sub errproc: msgbox 传输数据失败, vbcritical, 网络传输 end sub (3)线圈状态显示及寄存器读出数据显示 private sub winsock1_dataarrival(byval bytestotal as long) dim strdata() as byte dim i, j as integer dim s as string dim s1 as string dim io as byte i = winsock1.bytesreceived redim strdata(i) winsock1.getdata strdata, vbbyte, i for j = 0 to i - 1 s = s + hex(strdata(j)) next if s like *5* then s1 = mid(s, 12, 2) if s1 = ff then io = 1 a = &h0 else io = 0 a = &hff end if if io = 1 then shape1.fillcolor = rgb(0, 255, 0) green labl3.caption = io点接通 else shape1.fillcolor = rgb(255, 0, 0) red labl3.caption = io点断开 end if end if if s like *3* then text3.text = text3.text + mid(s, 11) + end if (4)、读多个寄存器数据 end sub private sub command4_click() on error goto errproc dim str(12) as byte str(0) = &h0 交换识别号高字节,通常为 0 str(1) = &h0 交换识别号低字节,通常为 0 str(2) = &h0 协议识别号高字节,为 0 str(3) = &h0 协议识别号低字节,为 0 str(4) = &h0 字节长度高字节 str(5) = &h6 以下字节长度低字节 str(6) = &hff 单元识别号,确省为 255 str(7) = &h3 读多个寄存器命令代码 str(8) = &h10 读数据的起始地址高字节 str(9) = &hc8 读数据的起始地址低字节 str(10) = &h0 数据长度高字节 str(11) = &h1 数据长度低字节 dim bstr as string dim i as integer for i = 0 to 11 bstr = bstr & chr(str(i)) next winsock1.senddata bstr exit sub errproc: msgbox 传输数据失败, vbcritical, 网络传输 end sub