j2mod

时间:2017-08-27 10:31:31

标签: java serial-port modbus

你好我使用j2mod与我的modbus设备串行连接,我得到了异常com.ghgande.j2mod.modbus.ModbusSlaveException:非法数据地址 那里的任何人都可以帮助我。以下是我的代码。

public static void main(String[] args) throws Exception {
    SerialConnection con = null;
    ModbusSerialTransaction trans = null;
    ReadMultipleRegistersRequest req = null;
    ReadMultipleRegistersResponse res = null;

    String portname= "COM4"; //the name of the serial port to be used
    int unitid = 1; //the unit identifier we will be talking to
    int ref = 41799; //the reference, where to start reading from
    int count = 100; //the count of IR's to read
    int repeat = 1; //a loop for repeating the transaction

   // ModbusCoupler.createModbusCoupler(null);
    ModbusCoupler.getReference().setUnitID(1);

    SerialParameters params = new SerialParameters();
    params.setPortName(portname);
    params.setBaudRate(19200);
    params.setDatabits(8);
    params.setParity("None");
    params.setStopbits(1);
    params.setEncoding(Modbus.SERIAL_ENCODING_RTU);
    params.setEcho(false);

    //4. Open the connection
    con = new SerialConnection(params);
    con.open();

    //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.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);

    //8. Close the connection
    con.close();  
}

1 个答案:

答案 0 :(得分:0)

非法数据地址是一个Modbus异常,表示您正在尝试访问不存在的寄存器。

在您的代码中,您尝试访问寄存器41799-42798。您的设备可能没有这些寄存器。

相关问题