Spirik / GEM

Good Enough Menu for Arduino
GNU Lesser General Public License v3.0
245 stars 36 forks source link

Passing parameters to GEMItem buttonAction function. #44

Closed manuelgonzalvez closed 2 years ago

manuelgonzalvez commented 2 years ago

Hi. i'm trying to call a function passing a parameter to it, depending on the button i'm clicking, so as not to have to create as many functions as buttons i have. All without success. Is it posible?

Spirik commented 2 years ago

Hi!

Unfortunately, currently there is no easy and straightforward way to achieve this, as was discussed here (one suggested solution was to try to pass a lamda function as a callback function, but apparently that still won't work as expected).

manuelgonzalvez commented 2 years ago

Thanks!

Spirik commented 2 years ago

Hello, @manuelgonzalvez !

Not sure if this is still relevant, but just wanted to let you know that with the latest release of GEM user-defined callback arguments are now supported (for buttons and for menu items that represent editable variables).

For that to work, callback function should expect argument of the type GEMCallbackData, which will hold user-defined value (any of the supported types int, byte, float, double, boolean, const char*, void*) as well as a pointer to menu item. To define the value of the variable you can submit it as an argument to a constructor when creating menu item, or define it later with GEMItem::setCallbackVal() method.

void pressButton(GEMCallbackData callbackData);
GEMItem menuItemButton("Light Switch", pressButton, "light_switch_1"); // String "light_switch_1" is user-defined callback value

...

void pressButton(GEMCallbackData callbackData) {
  Serial.print("Button ID: ");
  Serial.print(callbackData.valChar); // Accessing user-defined callback argument
  Serial.print(" | Button title: ");
  Serial.println(callbackData.pMenuItem->getTitle()); // Accessing menu item title
}

More info can be found in corresponding sections of Readme and wiki.

Have a good day!