Modbus Sequential Reading

Hi Forum,

I am using this Modbus Master Library
https://github.com/electricimp/Modbus/tree/master/ModbusSerialMaster

To read from Modbus slave with address 0x01

modbus.read(0x01, MODBUSRTU_TARGET_TYPE.COIL, 0x0001, 1, function(error, result) {
  if (error) {
    server.error(error);
  } else {
    server.log(result);
  }
}.bindenv(this));

I need to read SEQUENTIALLY one after another from 32 different Modbus slave devices
How to do this ?

I don’t have modbus hardware available to test, but something like this might work:

function readNext(index) {
    modbus.read(index, MODBUSRTU_TARGET_TYPE.COIL, 0x0001, 1, function(error, result) {
        if (error) {
            server.error(error);
        } else {
            server.log(result);
        }
        if (index < 32) {
            readNext(index+1);
        }
    }.bindenv(this));
}
readNext(1);

Thank you for suggestion @phil

What would be the effect of doing this modification ?

function readNext(index) {
    modbus.read(index, MODBUSRTU_TARGET_TYPE.COIL, 0x0001, 1, function(error, result) {
        if (error) {
            server.error(error);
        } else {
            server.log(result);

            if (index < 32) {
                  readNext(index+1);
            }

        }
        
    }.bindenv(this));
}
readNext(1);

With that modification, if modbus.read() returns an error then it won’t be called for the remaining devices in your sequence.

This topic was automatically closed after 60 days. New replies are no longer allowed.