modbus-esp8266 icon indicating copy to clipboard operation
modbus-esp8266 copied to clipboard

Running multiple actions per loop, or waiting between actions

Open duluthmachineworks opened this issue 2 years ago • 1 comments

First, this is a great library, but I am having some issues figuring out how to make multiple actions (ex. read/write) work in the same loop.

Right now, I would like to execute a writeCoil operation and a readHreg operation every time the main loop runs. Ex. code:

if (!mb.slave()) {
      mb.writeCoil(0x01, 0x00, true); // write to coil
      mb.readHreg(0x01, 0x01, &reg1, 1); //read Hreg
      while (mb.slave()) {
        mb.task();
        delay(10);
      }
    };
}

This process doesn't work as expected. I can get this to work by duplicating the entire if statement for each operation type, but this is clunky and doesn't seem to be the right way to do it. Working code:

if (!mb.slave()) {
      mb.writeCoil(0x01, 0x00, true); // write to coil
      while (mb.slave()) {
        mb.task();
        delay(10);
      }
    };
    if (!mb.slave()) {
      mb.readHreg(0x01, 0x01, &reg1, 1); //read hreg
      while (mb.slave()) {
        mb.task();
        delay(10);
      }
    };
}

Is this behavior due to the need to wait for the write operation to complete (and the response to be received) before I can begin the read operation? I have tried adding delays, but that also does not work.

Any input would be helpful.

duluthmachineworks avatar Aug 29 '23 15:08 duluthmachineworks

Your second pice of code it's just as the library designed to work. That's because no any requests queue inside the library. So if you send next request before previous request have completed operation just returns false and do nothing. Your second sketch waits operation to complete that's correct behaviour. Indeed implementation caused by Modbus protocol design/

emelianov avatar Oct 14 '23 02:10 emelianov