Hi all,

This is my first post, I'm trying to perform linear interpolation from a lookup as shown below.

```
//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}
};
```

I have made the following function which performs linear interpolation which approximates the output current(x) for a given input flux(y) value from the formula,

x = x0 + (x1-x0)*((y-y0)/y1-y0)

where,

x0 --> lower bound of x

x1 --> upper bound of x

y0 --> lower bound of y

y1 --> upper bound of y

```
double linearInterpolate(double y, double data[][2])
{
double 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];
return (x0 + ((x1 - x0) * ((y - y0) / (y1 - y0))));
}
}
}
```

Next, I run the following code by calling the interpolate function and I get the following output

```
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
double y = 0.44;
x = linearInterpolate(y, current_vs_flux);
Serial.println("Drive Current : ");
Serial.println(x);
delay(1000);
}
```

OUTPUT:

Drive Current :

0.00

Now, instead of calling the function explicitly I perform the linear interpolation approximation in the loop function itself and get the following output

```
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)));
}
}
Serial.println("Drive Current : ");
Serial.println(x);
delay(1000);
}
```

OUTPUT

Drive Current :

370.00

I cannot seem to figure out why I'm always getting zero when calling the function explicitly. But when I do a linear interpolation without using the function in the loop function, it approximates proper.

Could someone please explain why this is happening? Could I have gone wrong somewhere? I would need to perform interpolation in different parts of a larger code and it would seem silly to do interpolation every time without a function.

Any help is much appreciated, looking forward to your reply.

Regards

Sid