Sequencing Multiple Sub Routine simplified???

Hello,

I am working on a fairly complex project with multiple fairly large subroutines, and I am looking for a simple way to sequence them using a simple add equation...

example

a1();
a2();
.
.
.
a18()

I would luv to replace it with something like

if (x>1){
x=x++;
a+x();
}

obviously the second one does not work, but it shows what I am looking for...

thanks

Richard Sr

C++ is not interpreted so you can't dynamically generate a function name to call. function names are gone once compiled :slight_smile:

you could create an array of function pointers and go through that array

I was affraid of that?

Can you show me examples of how you would use an arry for this?

Thanks

Richard Sr

try this with your serial console opened at 115200 bauds
(typed here so might be buggy :slight_smile: )

void a0() {
  Serial.println(F("In function a0"));
}
void a1() {
  Serial.println(F("In function a1"));
}
void a2() {
  Serial.println(F("In function a2"));
}
void a3() {
  Serial.println(F("In function a3"));
}
void a4() {
  Serial.println(F("In function a4"));
}

void (*functionPointers[])() = {&a0, &a1, &a2, &a3, &a4}; // the & is not needed, I use it to show my intent of having the address of the function but you could write {a0, a1, a2, a3, a4}
const byte nbFunctions = sizeof(functionPointers) / sizeof(functionPointers[0]);

void setup()
{
  Serial.begin(115200);
  for (byte p = 0; p < nbFunctions; p++) functionPointers[p]();
}

void loop() {}

you should see in the console

In function a0
In function a1
In function a2
In function a3
In function a4

as a side note carefull with the ++ operator, you don't writex=x++ but just x++;if you want to increment x

In the same vein :

unsigned long currentTime;
unsigned long funcStartTime;
unsigned long funcPeriod  = 2000;
byte funcIndex = 0;

void func0();   //function prototypes needed
void func1();
void func2();

void (*functions[])() = {func0, func1, func2};
const byte NUMBER_OF_FUNCTIONS = sizeof(functions) / sizeof(functions[0]);

void setup()
{
  Serial.begin(115200);
  functions[funcIndex]();
}

void loop()
{
  currentTime = millis();
  if (currentTime - funcStartTime > funcPeriod)
  {
    funcIndex++;
    funcIndex = funcIndex % NUMBER_OF_FUNCTIONS;
    funcStartTime = currentTime;
    functions[funcIndex]();
  }
}

void func0()
{
  Serial.println(F("in func0"));
}

void func1()
{
  Serial.println(F("in func1"));
}

void func2()
{
  Serial.println(F("in func2"));
}

Hey Great guys, ty I think that will help...

Now just need to sit down and figure it out.... Yes! I am Blond! :stuck_out_tongue:

Thanks agn

Richard Sr