Java MODBUS RTU master example code

martin picture martin · Oct 29, 2014 · Viewed 12.6k times · Source

I need to write Modbus RTU master app in Java that support 03 - Read Holding Registers and 16 - Write Multiple Registers.

I found three java libraries: jamod, j2mod, modbus4j. I try all of these libraries (I spend about 4 hours) and it still doesn't work.

Do you know any step-by-step tutorial or example code?

I'm using USB->RS-485 converter. If I testing in QModBus, it works good.

Thank you.

import java.io.File;
import com.serotonin.io.serial.SerialParameters;
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;

public class Modbus4JTest {

   public static void main(String[] args) throws Exception {  
        ModbusFactory factory = new ModbusFactory();
        SerialParameters params = new SerialParameters();
          params.setCommPortId("/dev/ttyUSB1");
          params.setBaudRate(9600);
          params.setDataBits(8);
          params.setStopBits(1);
          params.setParity(0);
        ModbusMaster master = factory.createRtuMaster(params);
        master.setTimeout(2000);
        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");
  }
}

.

import java.io.File;

import com.ghgande.j2mod.modbus.ModbusCoupler;
import com.ghgande.j2mod.modbus.io.ModbusSerialTransaction;
import com.ghgande.j2mod.modbus.msg.ModbusRequest;
import com.ghgande.j2mod.modbus.msg.ReadInputRegistersRequest;
import com.ghgande.j2mod.modbus.msg.ReadInputRegistersResponse;
import com.ghgande.j2mod.modbus.net.SerialConnection;
import com.ghgande.j2mod.modbus.util.SerialParameters;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

// -Djava.library.path="/usr/lib/jni/"
public class J2mod {
    public static void main(String[] args) throws Exception {
        File lock = new File("/var/lock/LCK..ttyUSB0"); 
        lock.delete();
        File lock1 = new File("/var/lock/LCK..ttyUSB1"); 
        lock1.delete();

        SerialConnection con = null; // the connection
        ModbusSerialTransaction trans = null; // the transaction
        //ReadInputRegistersRequest req = null; // the request
        ReadHoldingRegistersRequest req = null;
        ReadHoldingRegistersResponse res = null;
        //ReadInputRegistersResponse res = null; // the response
        String portname = null; // the name of the serial port to be used

        int unitid = 0; // the unit identifier we will be talking to
        int ref = 0; // the reference, where to start reading from
        int count = 0; // the count of IR's to read
        int repeat = 1; // a loop for repeating the transaction
        try {
            portname = "/dev/ttyUSB1";
            //System.setProperty("gnu.io.rxtx.SerialPorts", portname);
            unitid = 2;
            ref = 0;
            count = 4;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
        // 2. Set master identifier
        // ModbusCoupler.createModbusCoupler(null);
        ModbusCoupler.getReference().setUnitID(1);
        // 3. Setup serial parameters
        SerialParameters params = new SerialParameters();
        params.setPortName(portname);
        params.setBaudRate(9600);
        params.setDatabits(8);
        params.setParity("None");
        params.setStopbits(1);
        params.setEncoding("rtu");
        params.setEcho(false);
        // 4. Open the connection
        con = new SerialConnection(params);
        con.open();
        // 5. Prepare a request
        req = new ReadHoldingRegistersRequest(unitid, ref, count);
        //req = new ReadInputRegistersRequest(ref, count);
        //req.setUnitID(unitid);
        //req.setHeadless();
        // 6. Prepare a transaction
        trans = new ModbusSerialTransaction(con);
        trans.setRequest(req);
        int k = 0;
        do {
            trans.execute();
            res = (ReadInputRegistersResponse) trans.getResponse();
            //res = (ReadHoldingRegistersResponse) trans.getResponse();
            for (int n = 0; n < res.getWordCount(); n++) {
                System.out.println("Word " + n + "=" + res.getRegisterValue(n));
            }
            k++;
        } while (k < repeat);
        // 8. Close the connection
        con.close();
    }
}

Answer