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.