Go Down

Topic: define size of array in constructor (Read 738 times) previous topic - next topic

DeadDealer

Hi,

I want to make a library from one of my sketches (DycoLed). Everything works fine by now, but now I have a problem.

Quote

#include "dycoLed_t.h"

/*
DycoLed library, designed for USI inferface
 on ATmega85.
 */

// will be set in constucor (?)
const int LEDCOUNT = 3;

//...

// custom array which holds the color information
dycoLed_t dycoLed[LEDCOUNT];

// word array for the messages for the leds
byte ledMessageMSB_a[LEDCOUNT];
byte ledMessageLSB_a[LEDCOUNT];

// check if leds are already initialized
boolean isInit = 0;

//..........


At the moment I use a constant LEDCOUNT to set the size of my arrays and for the loops in my functions. When I change it, it works pretty good. But here comes the problem for the library.
The size of the arrays should be dynamic, therefore my lib should get the count of the used leds in the init method. But then it is already to late to change the size of the array.

example (not in my code):

Code: [Select]

int ledPin;   // value can be changed at any time

int anyNumber[];   //not valid without values or size


A normal variable can be changed at any time, but the size of an arry must be set right at the declaration, not later. This fact makes it very difficult to set the size of the arrays in the .cpp or .h file for the lib, because I don't know the count of used leds at this time.

Is there any method (or workaround) to solve this problem?
I could imagine one. Generate an array of objects from my lib. But then there would be copies of all functions I use, and that would be a mess, too.

Correct me if i'm wrong ;)


Greets

Nick Gammon

See this for ideas:

http://arduino.cc/forum/index.php/topic,104334.0.html
http://www.gammon.com.au/electronics

DeadDealer

Here the complete code:

http://pastebin.com/tiFSbQe7

and the header file:

http://pastebin.com/nHGhy232


Later it should work like this for the user who works with my lib:

Code: [Select]

// init of things
DycoLed myLeds(42); //set the amount of leds
//...

void setup() {
  myLeds.firstInit();
  //... other stuff
}

void loop() {
  //beautiful color things
myLeds.setLed(9, { 31, 0, 0 }); //Set the 10th led to red (only 5 bit per color)
myLeds.setLed(100, { 0, 12, 12 }); //must not work, but should not be a runtime error!
}


PaulS

Code: [Select]
  myLeds.firstInit();
Perhaps you've noticed Wire.begin(), Serial.begin(), etc. Consistency is a good thing.

DeadDealer


Code: [Select]
  myLeds.firstInit();
Perhaps you've noticed Wire.begin(), Serial.begin(), etc. Consistency is a good thing.

You are right, will change it, thx :)



See this for ideas:

http://arduino.cc/forum/index.php/topic,104334.0.html

Looks like this is what I searched for, will test it out!

Go Up