kochedykov / jlibmodbus

JLibModbus - is an implementation of the Modbus protocol v1.1b in java language. Java modbus library. It works. Welcome.
http://kochedykov.github.io/jlibmodbus/
Apache License 2.0
299 stars 128 forks source link

Always Get ReadTimeOut Error When Reading From Real Device. #71

Open coderkan opened 3 years ago

coderkan commented 3 years ago

Hi everyone,

First of all, thanks for this good library. I have a problem when using it in a real device.

I have a modbus device and a modbus usb converter to test it. I have successfully connected with ModbusPool GUI and get data successfully.

My Configuration is like below;

BaudRate: 9600
DataBits : 8
Parity: SerialPort.Parity.EVEN
StopBits: 1

My Sample Code like below;

This is a sample code, I always get ReadTimeOut error. I have no success when I try to read from a real device, ModBus Pool read successfully from the device. Have you got any ideas about that problem?

Regards Erkan

        SerialUtils.setSerialPortFactory(new SerialPortFactoryPJC());
        SerialParameters sp = new SerialParameters();
        Modbus.setLogLevel(Modbus.LogLevel.LEVEL_DEBUG);
        try {
            String[] dev_list = SerialPortList.getPortNames();
            if (dev_list.length > 0) {
                sp.setDevice(dev_list[0]);
                sp.setBaudRate(SerialPort.BaudRate.BAUD_RATE_9600);
                sp.setDataBits(8);
                sp.setParity(SerialPort.Parity.EVEN);
                sp.setStopBits(1);

                ModbusMaster m = ModbusMasterFactory.createModbusMasterRTU(sp);
                m.connect();

                int slaveId = 1;
                int offset = 0;
                int quantity = 10;
                try {
                    int[] registerValues = m.readHoldingRegisters(slaveId, offset, quantity);
                    // print values
                    for (int value : registerValues) {
                        System.out.println("Address: " + offset++ + ", Value: " + value);
                    }
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        }

modbus-error

dotsha747 commented 2 years ago

Are you sure dev_list[0] contains the name of the serial port your device is connected to? Maybe print it out and confirm. There may be more than one serial device.