I might not understand the question but maybe this is what your looking for.
You can combine related information in a struct or class; being more a C programmer than a C++ programmer, I use structs.
struct SERVOCONTROL
{
uint8_t servoNum;
uint8_t analogPin;
float (*calculator)(int16_t);
};
The servoNumber
and analogPin
are hopefully explaining themselves. float (*calculator)(int16_t)
is a pointer to a function that takes an int as an argument and returns a float; I've implemented that as you have to different calculations. You can implement 2 functions as shown below for the calculations.
// calculator function 1
float calc1(int16_t value)
{
Serial.println("calc1");
return (value - 512) / 51.2;
}
Next you can declare an array of servo controls as demonstrated below; note that the calculations don't match with your original as A4 and A5 on the Uno are not available when using I2C.
SERVOCONTROL servoControls[]
{
{0, A0, calc1},
{3, A3, calc2},
};
The below code demonstrates how you can loop through the elements of the array and how you can use the fields in an element.
// macro to calculate number of elements in any type of array
#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(x[0]))
// some constant value
const float ADC_mult = 2;
// calculator function 1
float calc1(int16_t value)
{
Serial.println("calc1");
return (value - 512) / 51.2;
}
// calculator function 2
float calc2(int16_t value)
{
Serial.println("calc2");
return (value - 512) * ADC_mult;
}
// struct to combine related information to control a servo
struct SERVOCONTROL
{
uint8_t servoNum;
uint8_t analogPin;
float (*calculator)(int16_t);
};
// array with servo control information
SERVOCONTROL servoControls[] =
{
{0, A0, calc1},
{1, A1, calc2},
};
void setup()
{
Serial.begin(57600);
Serial.print("There are ");
Serial.print(NUM_ELEMENTS(servoControls));
Serial.println(" elements in servoControls");
for (uint8_t cnt = 0; cnt < NUM_ELEMENTS(servoControls); cnt++)
{
// display the servo number
Serial.print("servoNum = "); Serial.println(servoControls[cnt].servoNum);
// display the analog input pin
Serial.print("analogPin = "); Serial.println(servoControls[cnt].analogPin);
// if a calculator was specified
if (servoControls[cnt].calculator != NULL)
{
// calculate servo position
float x = servoControls[cnt].calculator(analogRead(servoControls[cnt].analogPin));
// and print it
Serial.println(x);
}
}
}
void loop()
{
}
Example output (with floating analog inputs)
There are 2 elements in servoControls
servoNum = 0
analogPin = 14
calc1
-1.52
servoNum = 1
analogPin = 15
calc2
-254.00