如何使用jamod库打开串行连接?

时间:2019-02-04 14:02:58

标签: java modbus

我正在尝试使用jamod库编写程序。我在打开连接时遇到问题。我使用了网站上的示例。

import java.net.*;
import java.io.*;
import net.wimpi.modbus.*;
import net.wimpi.modbus.msg.*;
import net.wimpi.modbus.io.*;
import net.wimpi.modbus.net.*;
import net.wimpi.modbus.util.*;


public class Test {

public static void main(String[] args) {
    /* The important instances of the classes mentioned before */
    SerialConnection con = null; //the connection
    ModbusSerialTransaction trans = null; //the transaction
    ReadInputRegistersRequest req = null; //the request
    ReadInputRegistersResponse res = null; //the response
    ModbusCoupler modbusCoupler=null;
    /* Variables for storing the parameters */
    String portname= "COM5"; //the name of the serial port to be used
    int unitid = 1; //the unit identifier we will be talking to
    int ref = 2; //the reference, where to start reading from
    int count = 2; //the count of IR's to read
    SerialParameters params =null;

         modbusCoupler = ModbusCoupler.getReference();
         modbusCoupler.setUnitID(0);
         modbusCoupler.setMaster(true); 
    params = new SerialParameters();
    params.setPortName(portname);
    params.setBaudRate(9600);
    params.setDatabits(8);
    params.setParity("None");
    params.setStopbits(1);
    params.setEncoding(Modbus.SERIAL_ENCODING_RTU);
    params.setEcho(true);


     try {
         con = new SerialConnection(params);
         con.open();
         req = new ReadInputRegistersRequest(ref, count);
         req.setUnitID(unitid);
         req.setHeadless();
         trans = new ModbusSerialTransaction(con);
         trans.setRequest(req);
         trans.execute();
          res = (ReadInputRegistersResponse) trans.getResponse();
          for (int n = 0; n < res.getWordCount(); n++) {
            System.out.println("Word " + n + "=" + res.getRegisterValue(n));
          }
          con.close();  
        } catch (Exception ex) {
          ex.printStackTrace();
        }

}

}

我遇到错误:

java.lang.Exception 
at net.wimpi.modbus.net.SerialConnection.open(SerialConnection.java:91)
at Test.main(Test.java:43)

似乎我的参数错误,但是我使用了测试程序,并且我知道它们很好。

有什么主意吗?

0 个答案:

没有答案