|Sharp GP2Y0A710K0F sensor|
I tried to do this with Gnuplot but found that using Excel or Calc is infinitely easier.
The voltage measurement versus distance for these sensors is non-linear. Here's a plot of the values I experimentally collected from a GP2Y0A710K0F 100-550cm sensor.
This line can be fit using a power function of the form:
Simply edit the plot, right click on one of the data points and select Insert Trend Line...
Then select Power under the Regression Type section then click the Show Equation checkbox.
You now get a trendline with the equation on your plot.
The equation works out to be:
To avoid the cpu- and memory-intensive math on an integer-only MCU, a faster option is to use a lookup table and interpolate between adjacent entries. This could be done with floating point or integer math. Store the range values multiplied by 100 for greater precision in the interpolation.
Also of note, the IR rangers have a usable range. If an object is too far away, the range will be unreliable. Modify the adc function so that it returns a large value like 999 if the adc value is below the usable limit (around 300 in this case).
If the object is too close, the ranger reports distance incorrectly. The best solution is to place the ranger so that objects cannot be closer than the minimum distance.
I also like to set a lower range in software. In our case, an adc value of 500 or higher should report back the minimum distance of 100cm.
One final note, every sensor is a little different, so it might be a good idea to calibrate each one if precision is an issue.