bxparks / AceButton

An adjustable, compact, event-driven button library for Arduino that debounces and dispatches events to a user-defined event handler.
MIT License
385 stars 37 forks source link

How to correctly create array of buttons from existing buttons? #44

Closed neilbaldwin closed 4 years ago

neilbaldwin commented 4 years ago

I can create an array of buttons by doing this:

AceButtons buttons[4];

but what if I want to create individual buttons and then add those to an array? The reason I want to do this is so that I can add specifiy configs to each button in an array. My best guess is this:

AceButton button1; AceButton button2; AceButton button3; AceButton arrayOfButtons[] = {button1, button2, button3};

but I get errors that butto1, button2 etc. has no type but if I type them {AceButton button1 etc.) I get a redefinition error.

What's the correct way to do this?

Thanks and thanks for this amazing button library - I've tried quite a few and this is by far the best and most confgurable (and incredibly documented!)

Neil

neilbaldwin commented 4 years ago

After some more trial and error I managed to get this far which seems to work:

ButtonConfig config1; ButtonConfig config2; ButtonConfig config3; ButtonConfig config4; ButtonConfig buttonConfigs[4] = {&config1, &config2, &config3, &config4}; AceButton button1(&config1); AceButton button2(&config2); AceButton button3(&config3); AceButton button4(&config4); AceButton buttons[4] = {&button1, &button2, &button3, &button4};

Is that the correct way to aprroach it? This way I can have one button handling function and can itteratively set settings etc. by iterrating through the button array but I'm able to set certain parameters for specific buttons.

bxparks commented 4 years ago

Don't have too much time right this minute, so this might be a sloppy response, but maybe this will point you in the right direction.

Array of buttons: You can certainly store pointers to AceButton instances like you did. But you can also directly create arrays of AceButton. Take a look at this example: https://github.com/bxparks/AceButton/blob/develop/examples/ArrayButtons/ArrayButtons.ino The tricky part is the initialization of each button. Hopefully, the example code gives you enough info on how to call the init() method on each button.

Multiple ButtonConfig: Unless you have some special configuration requirements for each button, you may not need multiple instances of ButtonConfig. And if you can get away with just using one, you can use the default SystemButtonConfig that's automatically created for you. Take a look the blurb that I wrote about Multiple Buttons at https://github.com/bxparks/AceButton#multiple-buttons

neilbaldwin commented 4 years ago

Thank you Brian.

Ah, the init() method was staring me in the face and it didn't click. I even had it in my old code but I forgot that you can pass a pointer to a ButtonConfig as the optional first parameter.

Thank you for your help!