GP2Y0A02YK Infrared Sensor in Real Distance

Submitted by Evan Boldt on Fri, 02/08/2013 - 14:12
Topics

Introduction

This is a longer range version of the GP2Y0D810 Infrared Sensor. They're about 15$, and work fairly well for distances between 0.5 meters and 1.5 meters. It is important to note that the distance to voltage curve is not linear. So, if you want the real distance, measured in mm, you'll need to come up with a best fit curve based on some experimental data.

Like the midrange version, the wiring is easy. Red goes to +5V, Black goes to GND, and white goes to an analog pin (in my case A0). You can even hook multples of them up as long as you use a seperate white to analog pin.

Again, IR does not the same on all surfaces. It depends on their reflectivity. For example, black surfaces tend to appear to be really far away since they don't bounce back much light. So, when you gather your data to make a best fit curve, you should use a surface similar to the one you plan on detecting.

Collect Some Data

I used 5V input voltage hooked up to an Arduino's analog read pin. I laid down a measuring tape and recorded the output from analogRead() at each distance. Here are the results:

Graph of Voltage vs Millimeters

Fit the Data

I think a polynomial regression would best fit the curve. I used a cubic polynomial. Here are the coefficients that I found based on my samples:

-0.00003983993846 v3+ 0.0456899769 v2 - 17.48535575 v + 2571.052715

Convert to Code

Once you have a good fit curve, the code is fairly straightforward:

//some globals used for averaging the samples

int numSamples = 0;
long irSum = 0;

//convert voltage to millimeters
int convertIRvoltsToMM(float v) { 
    return -0.00003983993846*v*v*v+ 0.0456899769 *v*v - 17.48535575 * v + 2571.052715; 
}


void setup() {}

void loop() {
    irSum += analogRead(A0);
    numSamples++;


    if ( numSamples >= 10 ) {
        int distance = convertIRvoltsToMM( float(irSum) / float(numSamples) );

        Serial.println( distance );
        irSum = numSamples = 0;
    }
}

Conclusion

It may be a good idea to take samples at a somewhat rapid frequency and average them together to produce more accurate results. Even after doing this, mine still fluctuates by a couple of centimeters even in its acurrate range. There is a chance this could be cleaned up with a better electronic circuit though.

You can also hook up two of these, take samples from both of them, and average the two. They do not seem to interfere with each other too much.

The variability of detection with reflection surface colors is also a pretty significant drawback. It is enough of a drawback that if you are really looking to measure anything in real distance, you probably should not use them. They probably work better as "threshold" detectors, where they are triggered once it reaches a certain voltage.

Attachments