Typedef a function pointer that returns void and accepts an unsigned long
Make an array of the function pointers
Make an array of unsigned long called last_run
Make an array of unsigned long called period
In the main loop, read the current time with "()". Check the last_run and period array, if the elapsed time is larger than the period, call the correct function pointer by index
Assistant
Certainly! Here's an example of Arduino C++ code that typedefs a function pointer, creates arrays of function pointers and unsigned long values, and calls the appropriate function based on elapsed time:
// Function declarations
void function1(unsigned long time);
void function2(unsigned long time);
void function3(unsigned long time);
// Array of function pointers
FunctionPointer functions[] = {function1, function2, function3};
// Array of last run times
unsigned long last_run[] = {0, 0, 0};
// Array of periods
unsigned long period[] = {1000, 2000, 500};
void setup() {
// Setup code here
}
void loop() {
unsigned long current_time = ();
for (int i = 0; i < sizeof(functions) / sizeof(functions[0]); i++) {
if (current_time - last_run[i] >= period[i]) {
functionsi;
last_run[i] = current_time;
}
}
// Other code in the loop
}
void function1(unsigned long time) {
// Code for function 1
// Do something with the time value
// Example: Serial.println("Function 1 called at time: " + String(time));
}
void function2(unsigned long time) {
// Code for function 2
// Do something with the time value
// Example: Serial.println("Function 2 called at time: " + String(time));
}
void function3(unsigned long time) {
// Code for function 3
// Do something with the time value
// Example: Serial.println("Function 3 called at time: " + String(time));
}
In this code, we typedef a function pointerFunctionPointerthat takes anunsigned longargument and returnsvoid. We create an array of function pointersfunctionsand initialize it with the addresses of the actual functionsfunction1,function2, andfunction3.
We also create arrayslast_runandperiodto store the last run times and periods of each function, respectively.
In theloop()function, we retrieve the current time usingmillis()and iterate through the arrays of functions, checking if the elapsed time is larger than the corresponding period. If it is, we call the function using the function pointer and update the last run time.
You can modify the code inside each function to perform the desired actions based on the elapsed time.