smarmengol / Modbus-Master-Slave-for-Arduino

Modbus Master-Slave library for Arduino
GNU Lesser General Public License v2.1
473 stars 328 forks source link

New Modbus requests are sent before all are read #69

Open felipepardo87587 opened 2 years ago

felipepardo87587 commented 2 years ago

Great library! Many thanks to the author.

Just spent a lot of time debugging a strange problem, I am using a heavily modified version of this library to read about 300 registers from a PLC. Leaving this here in case it saves somebody the time.

BUG: When the uC is busy and does not read the Serial buffer, a new Query may be sent before the buffer is emptied, this causes an offset, after which, the data is stored in the incorrect au16reg, because it's the response to a previous query. I modified the Modbus::query function as follows:

int8_t Modbus::query( modbus_t telegram ) { port->flush(); //Waits for the transmission of outgoing serial data to complete. while ( port->available() ) port->read(); //Clears RX buffer before sending a new query