1、引入modbus协议的依赖
<dependency>
<groupId>com.intelligt.modbus</groupId>
<artifactId>jlibmodbus</artifactId>
<version>1.2.9.9</version>
</dependency>
2、上代码
通过tcp读取以及写入数据
try {
// 设置主机TCP参数
TcpParameters tcpParameters = new TcpParameters();
// 设置TCP的ip地址
InetAddress adress = InetAddress.getByName("192.168.2.100");
// TCP参数设置ip地址
// tcpParameters.setHost(InetAddress.getLocalHost());
tcpParameters.setHost(adress);
// TCP设置长连接
tcpParameters.setKeepAlive(true);
// TCP设置端口,这里设置是默认端口502
tcpParameters.setPort(Modbus.TCP_PORT);
// 创建一个主机
ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
Modbus.setAutoIncrementTransactionId(true);
int slaveId = 1;//从机地址
int offset = 0;//寄存器读取开始地址
int quantity = 10;//读取的寄存器数量
try {
if (!master.isConnected()) {
master.connect();// 开启连接
}
// 读取对应从机的数据,readInputRegisters读取的写寄存器,功能码04
int[] registerValues = master.readHoldingRegisters(slaveId, offset, quantity);
int[] registers = {10}; // 要写入的数据
// 写入数据到寄存器
master.writeMultipleRegisters(slaveId, 7, registers);
// 控制台输出
for (int value : registerValues) {
System.out.println("Address: " + offset++ + ", Value: " + value);
}
} catch (ModbusProtocolException e) {
e.printStackTrace();
} catch (ModbusNumberException e) {
e.printStackTrace();
} catch (ModbusIOException e) {
e.printStackTrace();
} finally {
try {
master.disconnect();
} catch (ModbusIOException e) {
e.printStackTrace();
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
通过串口读取数据
ModbusRTU modbusRTU = new ModbusRTU();
int[] com9s = modbusRTU.read("COM9", 1, 10);
for (int i = 0; i < com9s.length; i++) {
System.out.println(com9s[i]);
}