RTU example
-
Hi All,
Downloading Modbus4J-src from sourceforge, you get a file, called Test.java helping you to set up a Modbus/Tcp master ..
Is something similar available for Modbus RTU?
The device I'm having supports only the following instructions:
03 (0x03) Read Holding Registers
04 (0x04) Read Input Registers
06 (0x06) Write Single Register
16 (0x10) Write Multiple Registers
17 (0x11) Report Slave IDIn the Modbus specification, register numbers are documented as "one based", but transmitted as "zero based" -- How are the frames created in Modbus4J for the RS485 bus? 1000 is 1000 (0x03E8) or 1001?
many thanks
-
Is something similar available for Modbus RTU?
Yes. Just use the factory to create an RTU master.
1000 is 1000 (0x03E8) or 1001?
There are multiple ways of creating locators in Modbus4J, but in all cases registers are specified zero-based. If you provide the register range - e.g. "coil" - your register will be 0. If you don't provide the register range (using a different constructor) it will be 1000.
-
Thank you Matthew.
I was able to use the factory and create the RTU master. The issue I was having was related with the definition of the serial parameters .. This is the code I came up with. It works .. knowing that the slave I'm reading from has the ID 7, and the connection over RS485 (COM6 here) is of "N81" type, at 9600 baudrate .
package appliancemb; import com.serotonin.modbus4j.ModbusFactory; import com.serotonin.modbus4j.ModbusMaster; import com.serotonin.modbus4j.code.DataType; import com.serotonin.modbus4j.code.RegisterRange; import com.serotonin.modbus4j.exception.ModbusInitException; import com.serotonin.io.serial.*; // declare variables public class appliance { public static void main(String[] args) throws Exception { ModbusFactory factory = new ModbusFactory(); SerialParameters params = new SerialParameters(); params.setCommPortId("COM6"); params.setBaudRate(9600); params.setDataBits(8); params.setStopBits(1); params.setParity(0); ModbusMaster master = factory.createRtuMaster(params); // master.setRetries(4); master.setTimeout(1000); master.setRetries(0); long start = System.currentTimeMillis(); // Don't start if the RTU master can't be initialized. try { master.init(); } catch (ModbusInitException e) { System.out.println( "Modbus Master Init Error: " + e.getMessage()); return; } try { System.out.println("Reg. 1001 Value:" + master.getValue(7, RegisterRange.HOLDING_REGISTER, 1000, DataType.FOUR_BYTE_FLOAT_SWAPPED)); // more like the above until all required register values are read. // .. } finally { master.destroy(); } System.out.println("Time elapsed: " + (System.currentTimeMillis() - start) + "ms"); } }
Thanks again.