Mod Master

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

VAR_EXTERNAL

END_VAR

VAR_GLOBAL

END_VAR

VAR

inst0_MODBUS_TCP_MASTER_INIT:MODBUS_TCP_MASTER_INIT;
inst1_MODBUS_TCP_MASTER_CTRL:MODBUS_TCP_MASTER_CTRL;

mConfirm:bool;
mError:usint;
mErrorinfo:usint;

mIP:udint;

mSocket:INT:=-1;

first:bool:=false;

mCtrl:bool:=false;
mDone :bool:=false;

modbusBuf : ARRAY[0..50] OF byte;


data_Ptr : POINTER;

DI0 AT %I0.0:byte;

addr:dword;
rw :usint;
mCount:int;
err:usint;

enConnect:bool:=true;
isConnect:bool:=false;

conTime:int:=0;

END_VAR

***********************************************************************************
**************************************************************************

mIP := LAN_ASCII_TO_INET('192.168.1.50');
inst0_MODBUS_TCP_MASTER_INIT(EN_IN :=enConnect,
NETNUMBER :=1 ,
MODE :=1 ,
REMOTE_IP_ADDR :=mIP ,
REMOTE_PORT :=502
| mSocket:= SOCKET_ID,
mConfirm:= EN_OUT,
mError := ERROR);
if mSocket=-1 then
enConnect:=false;
conTime:=conTime+1;
if conTime>1000 then
enConnect:=true;
conTime:=0;

end_if;

end_if;

if mConfirm=1 and mError=0 and mSocket>=0 then


isConnect:=true;
mCtrl:=true;
enConnect:=false;
end_if;

if isConnect=true then

data_Ptr:=&modbusBuf;
if DI0>0 then
mCtrl:=1;
if DI0=1 then
rw:=0; (*read*)
addr:=16#00001; (*read io 0 fc=1*)
mCount:=1;
elsif DI0=2 then
rw:=0; (*read*)
addr:=16#10001; (*read io 0 fc=2*)
mCount:=1;
elsif DI0=4 then
rw:=0; (*read*)
addr:=16#40001; (*read reg 0 fc=3*)
mCount:=2;
elsif DI0=8 then
rw:=0; (*read*)
addr:=16#30001; (*read reg 0 fc=4*)
mCount:=2;

elsif DI0=16 then


rw:=1; (*write*)
addr:=16#00001; (*read io 0 fc=5*)
mCount:=1;
modbusBuf[0]:=16#ff;
modbusBuf[1]:=16#00;

elsif DI0=32 then


rw:=1; (*write*)
addr:=16#00001; (*read io 0 fc=f*)
mCount:=8;
modbusBuf[0]:=16#01;
modbusBuf[1]:=16#ff;

elsif DI0=64 then


rw:=1; (*write*)
addr:=16#40001; (*read io 0 fc=6*)
mCount:=1;
modbusBuf[0]:=16#01;
modbusBuf[1]:=16#02;

elsif DI0=128 then

rw:=1; (*write*)
addr:=16#40001; (*read io 0 fc=10*)
mCount:=2;
modbusBuf[0]:=16#00;
modbusBuf[1]:=16#01;
modbusBuf[2]:=16#00;
modbusBuf[3]:=16#02;
end_if;

else

mCtrl:=0;

end_if;

if mCtrl=1 then
err:=0;
end_if;

inst1_MODBUS_TCP_MASTER_CTRL(
ENABLE :=mCtrl (*发送数据使能,上升沿触发*)
,NETNUMBER :=1 (* 网口设置 1*)
,SOCKET :=mSocket
, SLAVEID :=1 (*从站 id*)
, READWRITE :=rw (*0=读数据,1=写数据*)
, ADDRESS :=addr (*PLC 地址,例如:0x40001*)
, COUNT :=mCount (*读写数量*)
, DATA_PTR :=data_Ptr(*输入输出数据*)
| mDone:= DONE(*0=正在执行,1=执行结束*)
, mError := ERROR); (*0=无错误,错误信息*)

if mDone=1 and mError>0 then


err:=mError;
if err=254 then
isConnect:=false;
enConnect:=true;
end_if;
end_if;

end_if;

(*
ERROR:
0xff:端口未初始化
0xfe:端口号错误
0x10:从站 id 错误
0x11:读写功能错误
0x12:读写数量错误
0x04:读写数据错误
0x03:读写地址错误
0x13:功能选择不允许
0x20:功能码超范围
0x21:接收数据读写长度错误
0x50:接收数据从站 id 错误
0x60:接收数据功能码错误
0x30:超时

*)

You might also like