The Sharp distance sensors are a popular choice for many projects that require accurate distance measurements. This IR sensor is more economical than sonar rangefinders, yet it provides much better performance than other IR alternatives. Interfacing to most microcontrollers is straightforward: the single analog output can be connected to an analog-to-digital converter for taking distance measurements, or the output can be connected to a comparator for threshold detection. The detection range of this version is approximately 10 cm to 80 cm (4" to 32"); a plot of distance versus output voltage is shown below.

The GP2Y0A21 uses a 3-pin JST connector that connects to our 3-pin JST cable for Sharp distance sensors (not included) as shown in the upper picture on the right. It is also simple to solder three wires to the sensor where the connector pins are mounted (see the lower picture to the right). When looking at the back, the three connections from left to right are power, ground, and the output signal.

NOTE: All Sharp sensors from DFRobot are shipped with JST cable.


connection diagram


Sample Code

/******** start code ********/
 *  created     2013-07-12
 *  by      lisper (
 *  function    test gp2d12, read value from A0
 *      VCC -- VCC
 *      GND -- GND
 *      Signal -- Analog 0

#define pin A0

void setup () {
    Serial.begin (9600);
    pinMode (pin, INPUT);

void loop () {
    uint16_t value = analogRead (pin);
    uint16_t range = get_gp2d12 (value);
    Serial.println (value);
    Serial.print (range);
    Serial.println (" mm");
    Serial.println ();
    delay (500);

uint16_t get_gp2d12 (uint16_t value) {
    if (value < 10) value = 10;
    return ((67870.0 / (value - 3.0)) - 40.0);

/******** end code ********/


For any questions, advice or cool ideas to share, please visit the DFRobot Forum.

More Documentation


Reference(See examples of similar sharp distance sensor.)

category: Product Manual category: SEN Series category: Sensors