modbus-esp8266
modbus-esp8266 copied to clipboard
Running multiple actions per loop, or waiting between actions
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, ®1, 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, ®1, 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.
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/