Perform Modbus RTU Command

rt, txt = mbo:cmd(adr, fnc, [tfmt, ttab, [rfmt, ms]] )
rt, txt = modbus.cmd(cpo, adr, fnc, [tfmt, ttab, [rfmt, ms]] )

Send a command with Modbus RTU and get the response.

Parameter Type Description
mbo object table Modbus Object
cpo object COM Port Object
adr integer Slave address
fnc integer Function Number
tfmt string Transmit data format string ([Modbus Format Strings])
ttab table Transmit data table
rfmt string Receive data format string ([Modbus Format Strings])
ms integer Receive timeout
Returns Type Description
rt table Values (as specified by rfmt)
txt string Any remaining data

The indexed tables ttab is used, along with tfmt, to create a command string that is passed to modbus.tx.
The reply formatting is optional.

For example, to write to register 1000:

modbus.cmd(cpo, 1, 16, 'WWBW', {1000, 1, 2, 7878})
-- Register 1000 will have 2 bytes written as 7878

The modbus.cmd method will then call modbus.rx, and any reply is pulled apart using the rfmt specifiers to create a table of results.

For example, the Read Holding Registers command (0x03) function will return a byte-count, followed by n x 16-bit values (rfmt = 'BWWW' for 3 values):

local t = modbus.cmd(cpo, 1, 3, 'WW', {2, 3}, 'BWWW')
if t
then
 -- t[1] = Number of bytes
 -- t[2] = register 0002
 -- t[3] = register 0003
 -- t[4] = register 0004
 _, reg1, reg2, reg3 = unpack(t)
end

Note the use of Lua's unpack(t) to turn a table into a list of separate values.

Note

Use modbus.rhr as a complete solution for Read Holding Registers
The above example is purely for education.