How to build a lookup table in C (SDCC compiler) with linear interpolation

Stefan picture Stefan · Aug 17, 2011 · Viewed 17.6k times · Source

For a LPC922 microcontroller (with SDCC) I want to create a lookup table with linear interpolation. Lets assume I got x and y values like

x=300 y=10,0201 
x=700 y=89,542 
x=800 y=126,452 
x=900 y=171,453 
x=1500 y=225,123

How can the code for a lookup table with linear interpolation look like, so I get for example for x=850 the right value for y ((171,453+126,452)/2)?

Answer

MetallicPriest picture MetallicPriest · Aug 17, 2011
typedef struct { double x; double y; } coord_t;

coord_t c[5] = 
{
    {300, 10.02},
    {700, 89.542},
    {800, 126.452}, 
    {900, 171.453}, 
    {1500,225.123}
};    

double interp( coord_t* c, double x, int n )
{
    int i;

    for( i = 0; i < n-1; i++ )
    {
        if ( c[i].x <= x && c[i+1].x >= x )
        {
            double diffx = x - c[i].x;
            double diffn = c[i+1].x - c[i].x;

            return c[i].y + ( c[i+1].y - c[i].y ) * diffx / diffn; 
        }
    }

    return 0; // Not in Range
}

int main(int argc, char** argv) 
{
    double y = interp( c, 850, 5 );
}