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
- Sharp GP2Y0A21 IR Ranger Sensor
- Arduino Board, Quantity: 1
Software Preparation
- Arduino IDE (compatible with standard Arduino boards): Download Arduino IDE
Wiring Diagram

Wiring Instructions:
- Sensor VCC → Arduino VCC
- Sensor GND → Arduino GND
- Sensor Signal → Arduino Analog Pin 0
Other Preparation Work
- Connect the Sharp GP2Y0A21 IR Ranger Sensor to the Arduino board following the wiring diagram.
- Open the Arduino IDE and create a new sketch.
- 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
- Upload the code to the Arduino board.
- Open the Serial Monitor (Tools > Serial Monitor) and set the baud rate to 9600.
- 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?
