Ira318
1
Is it possible to write an Array of functions? I have a 3x3x3 LED cube and I wrote a function for each LED.
void led1(){
topLayer();
digitalWrite(2, HIGH);
delayMicroseconds(speedTime);
digitalWrite(2, LOW);
delayMicroseconds(lowtime);
}
void led2(){
topLayer();
digitalWrite(4, HIGH);
delayMicroseconds(speedTime);
digitalWrite(4, LOW);
delayMicroseconds(lowtime);
}
void led3(){
topLayer();
digitalWrite(7, HIGH);
delayMicroseconds(speedTime);
digitalWrite(7, LOW);
delayMicroseconds(lowtime);
}
... and so on.
Is it possible to have an array of functions
ledArray[]={led1,led2,led16,led15,led13...};
yes:
#define NUMBER_OF_FUNCTIONS 3
void (*myFunction[NUMBER_OF_FUNCTIONS])();
void setup()
{
myFunction[0] = functionZero;
myFunction[1] = functionOne;
myFunction[2] = functionTwo;
}
void loop()
{
for (int i = 0; i < NUMBER_OF_FUNCTIONS; i++)
{
myFunction[i];
}
}
void functionZero()
{
}
void functionOne()
{
}
void functionTwo()
{
}
but sometimes you only need a parameter for one function instead of an array of functions
int ledpin = { 2, 4, 7 , 9, 10 };
...
void led(int pin)
{
topLayer();
digitalWrite(pin, HIGH);
delayMicroseconds(speedTime);
digitalWrite(pin, LOW);
delayMicroseconds(lowtime);
}
for (int i =0; i < 5; i++) led( ledpin[i] );
Although in C++, you'd typically use a polymorphic class for this type of thing:
class ThingDoer {
public:
virtual void doThing();
};
class Do1 : public ThingDoer {
void doThing() {}
};
class Do2 : public ThingDoer {
public:
const char *s;
Do2(const char *s) : s(s) {}
void doThing() {}
};
class Do3 : public ThingDoer {
public:
const int howToDo;
Do3(int howToDo) : howToDo(howToDo) {}
void doThing() {}
};
ThingDoer *things[] = {
new Do1(),
new Do2("Some Text"),
new Do1(),
new Do3(5),
};
int theThing = 0;
void setup() {
}
void loop() {
things[theThing++]->doThing();
if (theThing > sizeof(things) / sizeof(*things)) {
theThing = 0;
}
}