# Finding index of closest integer in an array

Hi,

I have non-linear thermistor and I have a table showing ADC analogRead values to temperature from -40 to 150 degrees C.
Now, let say I read the analogRead for thermistor and returns an integer 0 to 1023. How do I find the closest matching ADC number in my table?
I have tried to look at binary search, but I think it is used for finding exact match. Not good for me!!!

Thanks

Put your look up table into an array.
Get your reading an use a while loop to visit each array entry in turn seeing if the array entry is bigger than your input value.
The first time you find an entry that is greater than the input value then you make a note if the index at this point and end the while loop.
It is the index that contains the value you want.

FardinB:
I have tried to look at binary search, but I think it is used for finding exact match. Not good for me!!!

A binary search should be fine, as you can compare <= to each position.

FardinB:
How do I find the closest matching ADC number in my table?

If you are looking for an accurate result then rather than find the nearest entry you would find the pair of entries that were higher and lower than your value and do a linear interpolation between them. If you organise the table correctly (i.e. using the sensor value as an index with the corresponding temperature as the value and with the sensor values equally spaced) then you can calculate the index values (rather than search for them). However you organise the table, the interpolation is just a weighted average of the two values read from the table.

Can you use the table data to graph the curve and deduce a formula that will let you calculate the temp? Might be more memory efficient.

I HAVE THE FOLLOWING CODE BUT FOR SOME REASON THE INDEX i doesnâ€™t go more than 1. Every time i run the code it outputs i=1 rather than giving i=6. Please let me know what is wrong in my code.

int i;
float sensed_current = 0.106;
const int arysz=34;
int closest;

float current[34]={0.031,0.046,0.061,0.076,0.091,0.106,0.121,0.136,0.151,0.166,0.181,0.196,0.211,0.226,0.241,0.256,0.271,0.286,
0.301,0.316,0.331,0.346,0.361,0.376,0.391,0.406,0.421,0.436,0.451,0.466,0.481,0.496,0.511,0.526};
float dutycycle[34]={0.725,0.717,0.711,0.707,0.703,0.700,0.697,0.695,0.693,0.691,0.689,0.687,0.685,0.683,0.682,0.680,0.679,0.678,
0.676,0.675,0.674,0.672,0.671,0.670,0.669,0.668,0.667,0.666,0.665,0.664,0.663,0.662,0.661,0.660};
void setup() {
Serial.begin(9600);
float tempMinimum = abs(current[0]-sensed_current);
for (i=1;i<34;i++){
if (abs(current*-sensed_current)<tempMinimum){*
tempMinimum = abs(current*-sensed_current);
_
closest=i;_
_
Serial.println(i);_
_
break;}_
_
}_
delay(10);
_
}*_