java modbus-tcp 根据寄存器种类获取数据,demo
时间: 2023-08-11 19:44:34 浏览: 112
Modbus读取写入模拟量寄存器详细demo(modbus RTU 和 modbus TCP 都有)
3星 · 编辑精心推荐
以下是一个简单的Java Modbus-TCP示例,根据寄存器类型获取数据:
```java
import java.net.InetAddress;
import com.serotonin.modbus4j.*;
import com.serotonin.modbus4j.exception.ModbusTransportException;
public class ModbusTCPExample {
public static void main(String[] args) throws Exception {
// Define the Modbus TCP connection parameters
InetAddress inetAddress = InetAddress.getByName("localhost");
int port = 502;
// Create the Modbus master
ModbusMaster master = ModbusUtil.createModbusMasterTCP(inetAddress, port);
// Define the slave ID and the starting address of the registers to read
int slaveId = 1;
int startAddress = 0;
// Define the number of registers to read
int numRegisters = 10;
// Define the type of register to read (holding, input, coil, or discrete)
RegisterRange registerRange = RegisterRange.HOLDING_REGISTER;
// Read the registers and print the values
try {
// Read the registers
ReadResponse response = master.readInputRegisters(slaveId, startAddress, numRegisters, registerRange);
// Print the register values
for (int i = 0; i < numRegisters; i++) {
System.out.println("Register " + (startAddress + i) + " = " + response.getShortData()[i]);
}
} catch (ModbusTransportException ex) {
System.out.println("Modbus exception: " + ex.getMessage());
} finally {
// Close the Modbus master
master.disconnect();
}
}
}
```
在示例中,我们首先定义了Modbus TCP连接参数,包括IP地址和端口号。然后,我们创建Modbus主机,并定义要读取的寄存器的起始地址、数量和类型。最后,我们从Modbus主机读取寄存器的值,并将其打印到控制台上。
阅读全文