How can I send modbus message to the PLC

1 view (last 30 days)
I am trying to send and receive modbus messages between Wago PLC and MATLAB. Wago PLC is the master and matlab will be the slave.
(I checked my PLC programm with a modbus slave simulator and it works)
I can read the modbus message in matlab but I can not send a modbus message to the PLC.This is what I write in Matlab.
obj=udp('192.168.1.2',502); % Ip address and port number of my plc and i will use UDP connection
set(obj, 'LocalPort', 502); % local port is 502
fopen(obj);
Message_Taken=fread(obj);% i read the modbus message
%The message from the PLC is like this and this data is in double format in matlab;
84 %Transaction ID
63 %Transaction ID
0 %Protocol ID
0 %Protocol ID
0 %Length
13 %Length
0 %Unit Identifier
23 %Function Code
0 %Reference number for Read
0 %Reference number for Read
0 %number of words for read
2 %number of words for read
0 %reference number for write
1 %reference number for write
0 %word count for write
1 %word count for write
2 %byte count (2X word count for write)
0 %register value1
254 %register value1
Transaction_Id_1=uint16(Message_Taken(1,1));
Transaction_Id_2=uint16(Message_Taken(2,1));
Transaction_Id=uint16(Transaction_Id_1+Transaction_Id_2);%16b Transaction Identifier
Protocol_Id=uint16(0);% 0 for modbus
Lenghf =uint16(6);% number of following bytes
UnitID=uint16(0);
Function_Code = uint16(3);% I use Function code 3 in slave
UnitIDFunCod = uint16(UnitID + Function_Code); % Concatenation of UnitID & FunctionCode in one int16 word
ByteCount =uint16(2);% number of data bytes
DATA=int16(29); % data that needs to be sent
Message_Sent= [Transaction_Id;Protocol_Id;Lenghf;UnitIDFunCod;ByteCount;DATA] fwrite(obj,Message_Sent,'uint16'); fclose(obj); delete(obj);
It gives no errors but I dont see the sent data in my PLC. I am quite new to modbus and if you figure out my mistake please contact me mcclaynn@hotmail.com
  1 Comment
Raimundas Steponavicius
Raimundas Steponavicius on 3 Mar 2017
Hi Ferit,
Did you figure it out ? I am looking for the answers to the same question, but unsuccessfully so far.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!