My bad, I will post the entire code here. Basically the first time I'm calling the linearInterpolate() function and it gives the output as zero.
The second time I run it without calling linearInterpolate(), I perform the interpolation in the loop function.
1st time
//lookup table for forward current (mA) vs. normalized radiant flux. Key-value pair: {current, flux}
double current_vs_flux[][2] = {{50, 0},
{100, 0.13},
{150, 0.19},
{200, 0.25},
{250, 0.31},
{300, 0.36},
{350, 0.42},
{400, 0.47},
{450, 0.52},
{500, 0.57},
{550, 0.61},
{600, 0.66},
{650, 0.7},
{700, 0.75},
{750, 0.79},
{800, 0.83},
{850, 0.87},
{900, 0.91},
{950, 0.95},
{1000, 1}
};
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
double y = 0.44;
double x, x0, x1, y0, y1;
x = linearInterpolate(y, current_vs_flux);
Serial.println("Drive Current : ");
Serial.println(x);
delay(1000);
}
double linearInterpolate(double y, double data[][2])
{
double x, x0, x1, y0, y1;
for (int i = 0; i < sizeof(data) / (sizeof(data[0][0]) * 2); i++)
{
if (y > data[i][1] && y < data[i + 1][1])
{
y0 = data[i][1]; //lower bound
y1 = data[i + 1][1]; //upper bound
x0 = data[i][0];
x1 = data[i + 1][0];
x = x0 + ((x1 - x0) * ((y - y0) / (y1 - y0)));
}
}
return x;
}
OUTPUT
Drive Current :
0.00
2nd time
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
double y = 0.44;
double x, x0, x1, y0, y1;
for (int i = 0; i < sizeof(current_vs_flux) / (sizeof(current_vs_flux[0][0]) * 2); i++)
{
if (y >= current_vs_flux[i][1] && y <= current_vs_flux[i + 1][1])
{
y0 = current_vs_flux[i][1]; //lower bound
y1 = current_vs_flux[i + 1][1]; //upper bound
x0 = current_vs_flux[i][0];
x1 = current_vs_flux[i + 1][0];
x = x0 + ((x1 - x0) * ((y - y0) / (y1 - y0)));
}
}
//x = linearInterpolate(y, current_vs_flux);
Serial.println("Drive Current : ");
Serial.println(x);
delay(1000);
}
OUTPUT
Drive Current :
370.00
I'm using a Arduino Mega 2560.