Example Code for Arduino-Read Distance Value

Learn how to interface the Sharp GP2Y0A21 IR Ranger Sensor with Arduino and convert analog output to distance measurements.

Hardware Preparation

Software Preparation

Wiring Diagram

GP2y0a21_connect

Wiring Instructions:

  • Sensor VCC → Arduino VCC
  • Sensor GND → Arduino GND
  • Sensor Signal → Arduino Analog Pin 0

Other Preparation Work

  1. Connect the Sharp GP2Y0A21 IR Ranger Sensor to the Arduino board following the wiring diagram.
  2. Open the Arduino IDE and create a new sketch.
  3. Select the correct Arduino board (Tools > Board) and port (Tools > Port) in the IDE.

Sample Code

/******** start code ********/
/*
 *  created     2013-07-12
 *  by      lisper ([email protected])
 *  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 ********/

Result

  1. Upload the code to the Arduino board.
  2. Open the Serial Monitor (Tools > Serial Monitor) and set the baud rate to 9600.
  3. You will see the analog read value (0–1023) and calculated distance (in mm) printed every 500ms.

Additional Information

  • NOTE: All Sharp sensors from DFRobot are shipped with JST cable.
  • The GP2Y0A21 uses a 3-pin JST connector that connects to our 3-pin JST cable for Sharp distance sensors (not included).

Was this article helpful?

TOP