|
@@ -0,0 +1,64 @@
|
|
|
+package com.htyg.manger.controller;
|
|
|
+
|
|
|
+
|
|
|
+import com.ghgande.j2mod.modbus.Modbus;
|
|
|
+import com.ghgande.j2mod.modbus.io.ModbusSerialTransaction;
|
|
|
+import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersRequest;
|
|
|
+import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse;
|
|
|
+import com.ghgande.j2mod.modbus.net.SerialConnection;
|
|
|
+import com.ghgande.j2mod.modbus.util.SerialParameters;
|
|
|
+
|
|
|
+public class ModbusReader {
|
|
|
+
|
|
|
+ private static final String PORT_NAME = "/dev/ttyUSB0"; // 更改为你的串口名称
|
|
|
+ private static final int BAUD_RATE = 9600;
|
|
|
+ private static final int DATA_BITS = 8;
|
|
|
+ private static final int STOP_BITS = 1;
|
|
|
+ private static final int PARITY = 0;
|
|
|
+ private static final int TIMEOUT = 2000;
|
|
|
+
|
|
|
+ public static void main(String[] args) {
|
|
|
+ SerialParameters parameters = new SerialParameters();
|
|
|
+ parameters.setPortName(PORT_NAME);
|
|
|
+ parameters.setBaudRate(BAUD_RATE);
|
|
|
+ parameters.setDatabits(DATA_BITS);
|
|
|
+ parameters.setStopbits(STOP_BITS);
|
|
|
+ parameters.setParity(PARITY);
|
|
|
+ parameters.setEncoding(Modbus.SERIAL_ENCODING_RTU);
|
|
|
+ parameters.setEcho(false);
|
|
|
+
|
|
|
+ SerialConnection connection = new SerialConnection(parameters);
|
|
|
+
|
|
|
+ try {
|
|
|
+ connection.open();
|
|
|
+ ModbusSerialTransaction transaction = new ModbusSerialTransaction(connection);
|
|
|
+ ReadMultipleRegistersRequest request = new ReadMultipleRegistersRequest();
|
|
|
+ request.setUnitID(1); // Modbus设备的ID,通常为1
|
|
|
+ request.setReference(3000); // 寄存器起始地址
|
|
|
+
|
|
|
+ // 读取连续8个32位数字
|
|
|
+ request.setWordCount(16);
|
|
|
+
|
|
|
+ transaction.setRequest(request);
|
|
|
+ transaction.execute();
|
|
|
+
|
|
|
+ ReadMultipleRegistersResponse response = (ReadMultipleRegistersResponse) transaction.getResponse();
|
|
|
+ if (response != null) {
|
|
|
+ for (int i = 0; i < response.getWordCount(); i += 2) {
|
|
|
+ int value = response.getRegisterValue(i) << 16 | response.getRegisterValue(i + 1);
|
|
|
+ // 处理读取到的数据
|
|
|
+ System.out.println("Register " + (i / 2 + 3000) + ": " + value);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ System.out.println("Response is null.");
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ if (connection != null) {
|
|
|
+ connection.close();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|