ReadDiscreteInputsRequest in Modbus4j
The ReadDiscreteInputsRequest class is part of Modbus4J, and it's used to create a request for reading discrete input registers from a Modbus device.
Discrete inputs, also known as input contacts, are single-bit read-only values, often used to represent the state of a physical input, such as a switch or a sensor.
Here's an example of how you might use the ReadDiscreteInputsRequest class in Modbus4J:
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.FunctionCode;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import com.serotonin.modbus4j.serial.SerialPortWrapper;
public class Modbus4JExample {
public static void main(String[] args) {
ModbusFactory factory = new ModbusFactory();
SerialPortWrapper serialPortWrapper = new YourSerialPortWrapperImplementation(); // Replace with your implementation
ModbusMaster master = factory.createRtuMaster(serialPortWrapper);
master.setTimeout(500); // Set the timeout to 500ms
master.setRetries(2); // Set the number of retries to 2
try {
master.init();
int slaveId = 1; // The ID of the slave device
int startOffset = 0; // The starting address of the discrete inputs to read
int numberOfInputs = 10; // The number of discrete inputs to read
ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId, startOffset, numberOfInputs);
ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) master.send(request);
if (response.isException()) {
System.out.println("Exception response: " + response.getExceptionMessage());
} else {
boolean[] inputs = response.getBooleanData();
for (int i = 0; i < inputs.length; i++) {
System.out.printf("Input %d: %b%n", startOffset + i, inputs[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
master.destroy();
}
}
}In this example, a Modbus RTU master is created using the ModbusFactory. A ReadDiscreteInputsRequest is then created with the specified slave ID, starting address, and number of discrete inputs to read. The request is sent using the send() method of the ModbusMaster, and the response is parsed to display the input values.
当我使用上面代码的时候有一个疑惑,当numberOfInputs = 1时,inputs.length为8。这是为什么呢?
In Modbus4J, when using the ReadDiscreteInputsResponse, the getBooleanData() method returns an array of boolean values where each value represents one bit.
However, the issue you mentioned occurs because the Modbus protocol reads data in bytes, not bits. Even if you request just one input, the response will contain a full byte of data, which translates to 8 bits.
也就是说,每次读取都是整字节的,哪怕你是读取1位,它返回的还是8位,读取28位,返回的是32位。
最终你需要舍弃numberOfInputs长度之后的数据,因为它们是无效数据。
评论已关闭