Proramatically initialize arrays of library defined data types?

Status
Not open for further replies.

oddson

Well-known member
I'd like to be able to have objects initialized for libraries like BOUNCE and ResponsiveAnalgogRead without having to adjust the code for the number of entries other than setting a size constant.

E.g.

If I have
const int button_count = 5;

I'll need to have a BOUNCE array defined explicitly.


The easiest way I have to make the code quick to adjust to the number of inputs is to use comments to null out the unused part of a pre-defined larger array definition:

Code:
// initialize the bounce objects 
Bounce digital[] =   {
  Bounce(DIGITAL_PINS[0],BOUNCE_TIME), 
  Bounce(DIGITAL_PINS[1], BOUNCE_TIME),
  Bounce(DIGITAL_PINS[2], BOUNCE_TIME),
  Bounce(DIGITAL_PINS[3], BOUNCE_TIME),
  Bounce(DIGITAL_PINS[4], BOUNCE_TIME)[COLOR="#A9A9A9"]/*,
  Bounce(DIGITAL_PINS[5], BOUNCE_TIME),
  Bounce(DIGITAL_PINS[6], BOUNCE_TIME),
  Bounce(DIGITAL_PINS[7], BOUNCE_TIME),*/[/COLOR]
};

Is there any mechanism for the pre-compiler to replace this code with a macro or some other programming structure I'm not really up on.

It's not dynamic allocation as the size known at compile time but I don't know whether it's possible in Aurdino/Teensyduino.
 
Why not just a for loop? Something like:

Code:
#include "Bounce.h"

const uint8_t button_count = 5;
const uint32_t button_time = 10;

Bounce *digital[button_count];

void setup() {
  for (size_t i=0; i < button_count; i++) {
    digital[i] = new Bounce(i,button_time);
  }
}
 
Status
Not open for further replies.
Back
Top