J2Mod是一个Java编写的Modbus通信库,可以用于实现Modbus RTU服务器。以下是一个简单的示例,演示如何使用J2Mod库创建一个Modbus RTU服务器:
如果使用Maven,可以在pom.xml
文件中添加以下依赖项:
com.ghgande.j2mod j2mod 3.1.3
如果使用Gradle,可以在build.gradle
文件中添加以下依赖项:
implementation 'com.ghgande.j2mod:j2mod:3.1.3' // 使用最新版本
创建Modbus RTU服务器:
下面是一个简单的Modbus RTU服务器示例,监听在COM3串口上,地址为1:
import com.ghgande.j2mod.modbus.Modbus; import com.ghgande.j2mod.modbus.procimg.SimpleDigitalIn; import com.ghgande.j2mod.modbus.procimg.SimpleDigitalOut; import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage; import com.ghgande.j2mod.modbus.serial.SerialParameters; import com.ghgande.j2mod.modbus.serial.SerialPort; import com.ghgande.j2mod.modbus.serial.SerialUtils; import com.ghgande.j2mod.modbus.serial.SerialPortException; import com.ghgande.j2mod.modbus.serial.SerialPortFactory; import com.ghgande.j2mod.modbus.ModbusCoupler; public class ModbusRTUServerExample { public static void main(String[] args) { try { // Create a process image with a single coil at address 0 SimpleProcessImage spi = new SimpleProcessImage(); spi.addDigitalOut(new SimpleDigitalOut(true)); // Coil at address 0 spi.addDigitalIn(new SimpleDigitalIn(false)); // Input at address 1 // Set up the serial parameters SerialParameters serialParameters = new SerialParameters(); serialParameters.setCommPortId("COM3"); serialParameters.setBaudRate(SerialPort.BAUD_9600); serialParameters.setDatabits(8); serialParameters.setParity(SerialPort.PARITY_NONE); serialParameters.setStopbits(1); serialParameters.setEncoding(Modbus.SERIAL_ENCODING_RTU); serialParameters.setEcho(false); // Create the Modbus RTU serial port SerialPort serialPort = SerialPortFactory.create(serialParameters); serialPort.open(); // Set the serial port for ModbusCoupler ModbusCoupler.getReference().setMaster(false); ModbusCoupler.getReference().setUnitID(1); ModbusCoupler.getReference().setProcessImage(spi); ModbusCoupler.getReference().setSerialPort(serialPort); // Start the Modbus RTU server ModbusCoupler.getReference().start(); System.out.println("Modbus RTU server is running..."); // Wait forever (you can add your own logic here) while (true) { Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } } }
j2mod完整案例开源项目https://gitee.com/mzmedia/mz-media
🤵♂️ 个人主页:@帐篷Li的个人主页
✍🏻作者简介:专注智能物联网设备云管解决方案
🐋 希望大家多多支持,我们一起进步!😄
如果文章对你有帮助的话,
欢迎评论 💬 点赞👍🏻 收藏 📂 加关注+
技术交流,需求定制可以扫码添加,相互学习交流!