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.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Modbus client TCP : can't get readHreg to work

hemeleerse opened this issue · comments

I want to read 2 consecutive registers using Modbus Client TCP/
issue The return value is always zero. If I use a modbus query tool on my pc, I receive the correct data.

  • Can some provide an example of proven working code that reads multiple Hreg ?
  • Would it not be better to add a debugging option that prints the raw data sent and received ? That would help a lot !!

Here's the code. I use #define MODBUSIP_DEBUG. Below the code, you'll see the output of the debug
loop() {
mb.task();
// Modbus request
if (millis() > LastModbusRequest + 15000) {
if ( mb.isConnected(smainverter)) {
transaction = mb.readHreg(smainverter, 30784, &res, 2, nullptr, 3);
Serial.print("Transaction id= "); Serial.println(transaction);
while(mb.isTransaction(transaction)) { // Check if transaction is active
mb.task();
delay(10);
}
Serial.print("Value = "); Serial.println(res);
LastModbusRequest = millis();
}
else {
mb.connect(smainverter);
}
}
}

The output
23:05:55.504 -> Transaction id= 13
23:05:56.551 -> Value = 0
23:06:06.160 -> 0: Bytes available 9

After using a callback function on the readHreg to print the request result, it turns out to be 0x2 (Illlegal Data Address).
So the device is not recognizing the address sent by readHreg. How can I make visible what is exactly sent ?
This really is crucial for debugging.

Got it working with this code:

// Keep modbus alive
mb.task();
// Modbus request
if (millis() > LastModbusRequest + 15000) {
if ( mb.isConnected(smainverter)) {
transaction = mb.readHreg(smainverter, 30775, res, 2, cb, 3);
Serial.print("Transaction id= "); Serial.println(transaction);
while(mb.isTransaction(transaction)) { // Check if transaction is active
mb.task();
delay(10);
}
Serial.print("Value = "); Serial.println(res[0],HEX); Serial.println(res[1],HEX);
LastModbusRequest = millis();
}
else {
mb.connect(smainverter);
}
}