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

Trying to increment a Holding Register every time what the Master reads an expecific Holding Register...

WagnerDeQueiroz opened this issue · comments

I need understand how to work the modbus.OnGetHreg(register)...

What I need. Each timer whats the master try read an expecific Holding Register, I need increment or Decrement the reading, but I put this loop and I get random values.... I think this is increment x every time what loop runs...
Any hint about how I can get my objective?

void loop() {
 if (mb.onGetHreg(101))
 {
  x++;
   mb.Hreg(101,x);

   if (digitalRead(pinToLED01))
   {
     digitalWrite(pinToLED01, LOW);
     digitalWrite(pinToLED02, HIGH);
   }
   else
   {
     digitalWrite(pinToLED01, HIGH);
     digitalWrite(pinToLED02, LOW);
   }
 }

  mb.task();
  yield();
}

I'm afraid the goal is not clear for me.
Do you want to increase holding register value each time client reads the register ?

Hello @emelianov, I create a Holding register or Input Register,like 5 or 10 with a initial number, I like to check every time this register is read, it will be incremented or decremented with each reading.

Like

void setup() {
... 
mb.Hreg(101,x);
}
loop(){
 ...
  if mb.HregReaded(101)
{ x++;
  return x};
}

What the function modbus.OnGetHreg(register)...
does?

You have to do it like this:
Set up a callback function to be called every time a holding register is queried. In this function you change the register as you please:

uint16_t cb(TRegister* reg, uint16_t val) {
  x++;
  mb.Hreg(101, x);
  return val;
}

x must be a global variable, otherwise it will be out of scope.
In setup, you have to define the callback function (assuming that mb is your Modbus object):
mb.onGetHreg((101, cb);

I just realized that it might have to be return x; if you also want to return the new value to the client that reads the value, because otherwise just the old value will be returned, but I'm not sure, I didn't test it out, so please report back here which solution works in the end so that others will know which one is correct.

Also, if you want to perform different actions based on the holding register address, you can do something like uint16_t addr = reg->address.address; and then perform actions based on the value of addr instead of just doing it with a fixed address of 101.