IR distance sensor, Sharp GP2Y0A21

The Sharp GP2Y0A21YK0F: two round lenses that measure 10 to 80 cm and give the distance as a voltage. Aliases: GP2Y0A21YK0F, Sharp IR sensor.

An infrared LED behind one lens throws a spot, and a detector behind the other sees where the reflected spot lands, which moves with the distance. So the color of the object hardly matters, and the output is a distance, not a yes or no.

Pins

Pin What it does
VO The output voltage, the yellow wire.
GND Ground, the black wire.
VCC Supply, 4.5 V to 5.5 V, the red wire.

Properties

distance is how far away the object starts, in centimeters, 1 to 150.

While it runs

The slider is the distance to the thing in front of the sensor.

What the model gets right

From the Sharp datasheet:

The curve. 0.4 V typical at 80 cm and 1.9 V more than that at 10 cm, falling as the inverse of the distance in between. The model is the inverse curve through those two points: about 2.3 V at 10 cm, 1.37 V at 20 and 0.98 V at 30.

Too close. Under 10 cm the output falls again, so an object too close reads as one far away: 5 cm gives about what 25 cm does. The model keeps that trap, though not the exact shape of the real curve under 10 cm.

Timing. A new measurement every 38.3 ms. The output holds between them, and right after power-up it reads nothing until the first one.

What it does not model

The spread between parts (calibrate a real one), the small effect of very dark or shiny surfaces, sunlight, and the current spikes of the LED, which is why the datasheet asks for a capacitor across the supply.

Libraries

SharpIR (SharpIR.h) turns the reading into centimeters: SharpIR sensor(SharpIR::GP2Y0A21YK0F, A0); sensor.getDistance();

Common mistakes

Holding the hand closer than 10 cm and reading "far". Mount it so nothing can come that close, or back it off behind the edge of the robot.

See it in action

Distance rainbow lights a WS2812 stick from green to red as a hand comes closer. Open it at /templates.