I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.
ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc and would like to called them randomly in that fashion :
randNumber = random(1,11);
anim[randNumber]();
I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that.. I'm sure there must be a way ;)
thanks for your help
2 Answers 2
What you want is an array of function pointers.
void anim1() {
// blah blah
}
void anim2() {
// blah blah
}
// ... etc ...
typedef void (*animptr)();
animptr anims[10] = {
anim1,
anim2,
anim3,
// ... etc ...
anim10
};
Then you can use:
anims[animNumber]();
-
You mean
typedef void (*animptr)();
.Edgar Bonet– Edgar Bonet2016年05月21日 12:42:18 +00:00Commented May 21, 2016 at 12:42 -
I didn't know this was possible. But I think I would feel dirty when using it. It just seems wrong to do this.Gerben– Gerben2016年05月21日 13:46:07 +00:00Commented May 21, 2016 at 13:46
-
Why so? Function pointers are one of the most powerful facilities of C. Imagine trying to implement callbacks without being able to use function pointers - and an array of them is just an extension of that. A function is, after all, just a location in memory...Majenko– Majenko2016年05月21日 13:47:37 +00:00Commented May 21, 2016 at 13:47
-
thanks so much Majenko! exactly what i was looking for! :Drobophil– robophil2016年05月23日 00:56:27 +00:00Commented May 23, 2016 at 0:56
I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!
int randNumber;
void loop(){
randNumber = random(1,14);
if (button is pressed or something){
callAnim(randNumber);
}
}
void callAnim(int randNumber){
if (randNumber==1){
anim1();
}
if (randNumber==2){
anim2();
}
}
// ... etc ...
void anim1() {
// blah blah
}
void anim2() {
// blah blah
}
// ... etc ...