andresarmento / modbus-arduino

A library that allows your Arduino to communicate via Modbus protocol, acting as a slave (master in development). Supports serial (RS-232, RS-485) and IP via Ethernet (Modbus IP).
BSD 3-Clause "New" or "Revised" License
455 stars 267 forks source link

Callback function implementation for Coil/Hreg writes #9

Open TomaTLAB opened 8 years ago

TomaTLAB commented 8 years ago

Hi, Andre. It maybe a powerful mechanism for range checking, storing a values in EEPROM, etc.

word callback_hr1 (word val, byte src)
{
  print("Callback HR1 rised from ");
  print(src);
  print(" with value ");
  println(val);
  return val;
}

word callback_coil1 (word val, byte src)
{
  if (mb.Coil(1) == (bool)val) return val; // nothing todo
  if ((bool)val) digitalWrite(LED_PIN, LOW); else digitalWrite(LED_PIN, HIGH); // change pin state
  return val;
}

void setup() 
{
//......
  mb.addHreg(1, 12345,  callback_hr1);
  mb.addHreg(2);
  mb.addHreg(3);
  mb.addHreg(4);
  mb.addCoil(1, false, callback_coil1);

//...........
// somewhere in the code
  mb.Hreg(1, 321); //     printout: "Callback HR1 rised from 0 with value 321"
  mb.Hreg(1, 123, 100); // printout: "Callback HR1 rised from 100 with value 123"
// writing 456 via modbus printout: "Callback HR1 rised from 6 with value 456"
//.....
wvengen commented 8 years ago

I like the idea! It could also bring a performance benefit since the linked list only needs to be traversed once.

wvengen commented 8 years ago

I would have expected the second argument to the callback to be the from value, but reading the code I see it is a function code that initiated the change. Do you have a specific use-case for that?

TomaTLAB commented 8 years ago

Hi! I add this argument for tracking from where callback occur - inside the lib or in my own code, and make a decision on this info. I need to look in my code to remember for what I made it :)