Search code examples
javamodbusserial-communication

J2mod reading different value from holding register


I have successfully connected to my modbusRTU by using j2mod, when i tried to read the value from holding register ranging 40050 to 40054 i always get 28826,28828,28830,28832,28834. I don't know whats this value, please someone help.

 ModbusSerialTransaction trans = null;
       ReadMultipleRegistersRequest req = null;
       ReadMultipleRegistersResponse res = null;

       int unitid = 1; //the unit identifier we will be talking to
       int ref = 40050; //the reference, where to start reading from
       int count = 5; //the count of IR's to read
       int repeat = 1; //a loop for repeating the transaction

       //4. Open the connection
       try {

           //5. Prepare a request
           req = new ReadMultipleRegistersRequest(ref, count);
           req.setUnitID(unitid);
           req.setHeadless();

           //6. Prepare a transaction
           trans = new ModbusSerialTransaction(con);
           trans.setRequest(req);

           int k = 0;
           do {
               trans.setTransDelayMS(50);
               trans.execute();
               res = (ReadMultipleRegistersResponse) trans.getResponse();
               for (int n = 0; n < res.getWordCount(); n++) {
                   System.out.println("Word " + n + "=" + res.getRegisterValue(n));
               }
               k++;
           } while (k < repeat);
           con.close();
           //8. Close the connection
       } catch (ModbusException ex) {
          System.out.print(ex);
       }

please check this code.

Solution

  • As discussed in the comments, your problem turned out to be quite easy to solve: you were just using the wrong offset for the Modbus address you wanted to read.

    Modbus holding registers are by convention numbered starting from 40000, but for most libraries this offset is not to be considered.

    So to read register referred to as 40011 in the Modbus map of a certain device you have to use index number 10.

    By the same logic, to read register 40050 you just have to change the address line in your code:

    int ref = 49; //the reference, where to start reading from