This Modbus Master subroutine is very useful if you wish to use our incredible ACE PLC for read or write in a Modbus RTU Slave devices.

If you want to connect the ACE PLC to a variable frequency drive, an intelligent sensor, a simple display, remote I/O or even an ACE PLC !

This subroutine allow you to:

  • Read Holding Registers – Function code 03
  • Read Input Registers – Function code 04
  • Write Holding Registers – Function code 06

You can download the subroutine with its example here.

How does the Modbus Master subroutine work?

Your ACE PLC must be configured as Type = “Custom” serial port.

Import in your project the 2 subroutines via the “Add Subroutine” button :

  • MBCRC16
  • ModbusMaster

Define your Modbus requests to read and write data. It is very important to read the data first and then write the others.

In our example, we want to read and write this Modbus registers:

Number ” n ” of the Modbus Request Slave ID of the Modbus Slave Device
SlaveID[n]
Read or Write in the register ?
FunctionCode[n]
Address in the Modbus register ?
Register[n]
[0] 01 03 (Read Holding Registers) 00
[1] 01 03 (Read Holding Registers) 01
[2] 01 06 (Write Holding Registers) 02 (We write in 65432 in our example)
[3] 01 06 (Write Holding Registers) 03 (We write in the tag “ValueMove” in our example)

We use a array of “n” elements for each parameters

Setup these tags:

  • FunctionCode, ui8, is array, 16 (16 if you wish to read/write up to 16 values inthe Modus register)
  • SlaveID, ui8, is array, 16
  • Register, ui16, is array, 16
  • Data, ui16, is array, 16

 

If, as example, you have only 3 registers to read/write, you can adjust the array from 16 to 3.

 

 

Now, you can complete your array with the 3 values for each Modbus request:

We start with n = 0

  • SlaveID[0] = 01
  • FunctionCode[0] = 03
  • Register[0] = 00

and next… n = 1

  • SlaveID[1] = 01
  • FunctionCode[1] = 03
  • Register[1] = 01

< ! > Important: The last line must be SlaveID[n+1] = 00, in our example SlaveID[4] = 00
This is to alert the Modbus Master subroutine that there are no more registers to read! It is the end! We restart from the beginning (n=0)!

 

 

And just add now the ModbusMaster subroutine !

You must call this subroutine at each PLC cycle.

 

You will retrieve your data in the Data[n] array.

If you use the write function, do not forget to enter the value. In our example, we write 65432 in Data [2] and the value of another “ValueMove” tag in Data [3].