1

I'm trying to define an array of function pointers, where each function contains an int parameter. I'm also trying to set the value of that int parameter in the array declaration

So I have a TIMED_TASK struct, that will hold the function pointer and value I want to pass

typedef struct
{
   void (*proc)(int);  
   int delayMsec;     
} TIMED_TASK;

Then I have an array of TIMED_TASKs like this

static const TIMED_TASK attractSequence[] =
{
    { LightsOn, 1000 },
    { LightsOff, 500 },
    { EndSequence, 0 }
};

And I'd like it to call each of those functions in turn, passing the delay value to each function. This is where I expect I have the wrong syntax (I'm still learning C). I seemingly don't hit my LightsOn() routine at all

void loop() // It's an arduino project :)
{
  attractSequence[sequence];
  sequence++;
}

void LightsOn(int pause)
{
  // I do not hit this routine for some reason?
  Serial.print("LIGHTS ON"); 
  Serial.print(pause);
}

void LightsOff(int pause)
{
  Serial.print("LIGHTS OFF");
  Serial.print(pause);
}

It's entirely possible I'm taking the wrong approach here, but hopefully you can see what I'm trying to achieve. Any advice very welcome!

4
  • 1
    Are you sure this is straight up C? This looks like an embedded dialect like the arduino language. Commented Sep 25, 2015 at 21:37
  • Correct, it's an arduino project. But I believe the syntax should be the same as C? Commented Sep 25, 2015 at 21:37
  • It's not, Serial.print(pause) is invalid c, not entirely invalid but as it is in your code it seems to be. Also, you are never calling the function through the pointer, where do i expect it to be called in the posted code? Commented Sep 25, 2015 at 21:37
  • Arduino is not C Commented Sep 25, 2015 at 21:45

1 Answer 1

5

If you want to go through each item of attractSequence only once, you can use:

void loop()
{
   int count = sizeof(attractSequence)/sizeof(attractSequence[0]);
   for (int i = 0; i < count; ++i )
   {
     attractSequence[i].proc(attractSequence[i].delayMsec);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thank you. The syntax I needed was attractSequence[sequence].proc(attractSequence[sequence].delayMsec). Makes perfect sense now that I see it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.