3

I am trying to run below code. I have a MODBUS transmitter connected at COM1 with Baud rate of 9600, transmitting data via USB cable. I want to collect that data.

public static void main(String[] args) {
    SerialConnection con = null;
    ModbusSerialTransaction trans = null;
    ReadInputRegistersRequest req = null;
    ReadInputRegistersResponse res = null;

    String portname = null;
    int unitid = 0;
    int ref = 0; 
    int count = 0;
    int repeat = 1;

    try {
        portname = "COM1";
        unitid = 2;
        ref = 0;
        count = 8;
    } 
    catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
    ModbusCoupler.getReference().setUnitID(1);
    SerialParameters params = new SerialParameters();
    params.setPortName(portname);
    params.setBaudRate(9600);
    params.setDatabits(8);
    params.setParity("None");
    params.setStopbits(2);
    params.setEncoding("rtu");
    params.setEcho(false);
    con = new SerialConnection(params);
    con.open();
    req = new ReadInputRegistersRequest(ref, count);
    req.setUnitID(unitid);
    req.setHeadless();
    trans = new ModbusSerialTransaction(con);
    trans.setRequest(req);
    int k = 0;
    do {
        trans.execute();
        res = (ReadInputRegistersResponse) trans.getResponse();
        for (int n = 0; n < res.getWordCount(); n++) {
            System.out.println("Word " + n + "=" + res.getRegisterValue(n));
        }
        k++;
    } 
    while (k < repeat);
    con.close();
}       

While running the code, I am getting below error.

java.lang.Exception
at net.wimpi.modbus.net.SerialConnection.open(SerialConnection.java:91)
at Main.main(Main.java:50)
Exception in thread "main" java.lang.NullPointerException
at net.wimpi.modbus.io.ModbusSerialTransaction.execute(ModbusSerialTransaction.java:168)
at Main.main(Main.java:66)
While running,  

Please help me out in this, as i am not able to figure out the error.

Robert
  • 7,394
  • 40
  • 45
  • 64
Amar Shah
  • 89
  • 2
  • 9
  • What statements are at line 50 and line 60 in your Main.jave file? I suspect maybe "con.open()" and "trans.execute()". – Marker Jul 27 '18 at 20:25
  • "con.open()" opens the serial connection and "trans.execute()" is starting the transaction. – Amar Shah Jul 31 '18 at 01:51
  • Yes, I realize what they do, but java is saying there were exceptions at line 50 and line 66 (sorry I asked about 60 above). – Marker Jul 31 '18 at 19:28
  • I added try...catch block also for both of them, but it still gives same error – Amar Shah Aug 02 '18 at 02:07
  • Can you communicate with the device from another Modbus tool (ModScan32 or similar)? I suspect there is a wiring issue or issue with the port settings. It could have 2 stop bits as you have coded, but that's pretty uncommon. – Ken Aug 06 '18 at 20:30
  • I tried with RealTerm tool to communicate and its working fine out there – Amar Shah Aug 16 '18 at 05:32

0 Answers0