Start a new topic

How to pass argument to a function attached to button?

Hi, does anybody know how?

For exmple:
I have function: void Funct( byte X ){...}
and i have 2 buttons: b1, b2
now i want to attach my function to these buttons with different arguments. What do I need to write in setup? I was thinking about
b1.attachPop(Funct (1));

b1.attachPop(Funct (2));
but it wont work. 

Oh, forgot to say, I'm asking about arduino library.

And of course i mean  b2.attachPop(Funct (2));

A quick way to achieve this is using wrapper functions as follows: void wrap1() { Funct(1); } void wrap2() { Funct(2); } b1.attachPop(wrap1); b2.attachPop(wrap2);

Well, basically, it is the same as to write separate functions with same body but different arguments for each button. I was wondering if there is a way to handle the problem with only one function, but as far as I can see there is no such way. But anyway thank you for an answer. Good to know possible solutions. 

It's a C/C++ phenomenon. Wherever you attach a function, it's not the function call itself which is attached, but just a function pointer. That means just a memory address where the function can be found. That's why you can't pass parameters. The same "workaround" is needed when calling member functions of non static objects from "outside", i.e. from an interrupt handler.

In such cases, I favorize the wrapper solution though instead of writing two complete and almost identical function bodies. First, the compiled file will be smaller, and second, it's easier to maintain and to extend, especially when the function body is very complex.

Login or Signup to post a comment