emelianov / modbus-esp8266

Most complete Modbus library for Arduino. A library that allows your Arduino board to communicate via Modbus protocol, acting as a master, slave or both. Supports network transport (Modbus TCP) and Serial line/RS-485 (Modbus RTU). Supports Modbus TCP Security for ESP8266/ESP32.
Other
534 stars 190 forks source link

Running multiple actions per loop, or waiting between actions #306

Closed duluthmachineworks closed 6 months ago

duluthmachineworks commented 1 year ago

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.

emelianov commented 1 year ago

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/