Tags: , , ,

The sensor GP2Y0A21 is an infrared distance sensor from Sharp that can detect object located at a distance between 10 and 80cm in front of it.


  • Computer
  • Arduino UNO
  • USB A/B
  • GP2Y0A21

Operating principle

The distance sensor GP2Y0A21 uses infrared light to calculate the distance to an object by triangulation. An infrared LED sends a light signal invisible to the naked eye which is reflected in the presence of an object. A photoresist strip captures the light reflected thereby and deduce the reflection angle and thus the distance. The sensor sends an analog value between 0 and 5V.


The distance sensor is supplied with 5V. Pin Vcc of the sensor can be connected to the 5V microcontroller pin, the GND pin to ground of the microcontroller and the signal is connected to an analog input of the microcontroller.
GP2Y0A21 must be connected as shown below.


To display the physical value of the sensor, it is necessary to know the conversion rule. In order to have a clean and readable code, it is best to place the code in a sub function. We create a function that is responsible for reading the sensor value and convert physical value. Then, we read the raw value of the sensor using the analogRead () function and convert this value in centimeter. To detect obstacle, we define a threshold of 200 below which is considered an obstacle is detected.
To use GP2Y0A21 object we use the following code:

const int gp2y0a21Pin  = A0;

int gp2y0a21Val  = 0;

void setup() {
  //Init Serial USB
  Serial.println(F("Initialize System"));
  //Init ditance ir
  pinMode(gp2y0a21Pin, INPUT);

void loop() {

void testGP2Y0A21( ) { /* function testGP2Y0A21 */
  ////Read distance sensor
  gp2y0a21Val = analogRead(gp2y0a21Pin);
  Serial.print(gp2y0a21Val); Serial.print(F(" - ")); Serial.println(distRawToPhys(gp2y0a21Val));
  if (gp2y0a21Val < 200) {
    Serial.println(F("Obstacle detected"));
  } else {
    Serial.println(F("No obstacle"));

int distRawToPhys(int raw) { /* function distRawToPhys */
  ////IR Distance sensor conversion rule
  float Vout = float(raw) * 0.0048828125; // Conversion analog to voltage
  int phys = 13 * pow(Vout, -1); // Conversion volt to distance

  return phys;



Find more tutorials and examples in our code generator
Code Architect

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?