SHARP GP2Y0A21YK0F IR distance sensor

How to use a SHARP GP2Y0A21YK0F IR Distance Sensor with Arduino

The SHARP GP2Y0A21YK0F is an easy to use IR distance sensor with a range of 10 – 80 cm. It is a great sensor to use for autonomous robots or non-contact optical switches.

In this tutorial, you will learn how the sensor works and how to use it with Arduino. I have included a wiring diagram and example code so you can start experimenting with your sensor.

PCBWay

If you are looking for a more affordable or waterproof distance sensor, take a look at the HC-SR04 or JSN-SR04T. In the articles below I explain how these distance/proximity sensors work and how you can use them with Arduino.

Other distance/proximity sensors:


Supplies

Hardware components

GP2Y0A21YK0FSHARP GP2Y0A21YK0F IR distance sensor× 1Amazon
Arduino Uno Rev 3Arduino Uno Rev3× 1Amazon
Breadboard× 1Amazon
Jumper wires~ 10Amazon
capacitorCapacitor (10 µF or more)× 1Amazon
USB cable type A/B× 1Amazon

Software

Arduino IDEArduino IDE

Makerguides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to products on Amazon.com.


How does an IR distance sensor work?

An IR distance sensor uses a beam of infrared light to reflect off an object to measure its distance. The distance is calculated using triangulation of the beam of light. The sensor consists of an IR LED and a light detector or PSD (Position Sensing Device). When the beam of light gets reflected by an object, the reflected beam will reach the light detector and an ‘optical spot’ will form on the PSD.

How an IR distance sensor works light emitter and detector PSD

When the position of the object changes, the angle of the reflected beam and the position of the spot on the PSD changes as well. See point A and point B in the image below.

How an IR distance sensor works
Note the change in the angle of the reflected beam and the position of the ‘optical spot’ on the PSD.

The sensor has a built-in signal processing circuit. This circuit processes the position of the optical spot on the PSD to determine the position (distance) of the reflective object. It outputs an analog signal which depends on the position of the object in front of the sensor.


How to read an IR distance sensor?

IR distance sensors output an analog signal, which changes depending on the distance between the sensor and an object. From the datasheet, you can see that the output voltage of the SHARP GP2Y0A21YK0F ranges from 2.3 V when an object is 10 cm away to 0.4 V when an object is 80 cm away. The graph also shows why the usable detection range starts at 10 cm. Notice that the output voltage of an object that is 2 cm away is the same as the output voltage for an object that is 28 cm away. The usable detection range, therefore, starts after the peak at roughly 10 cm or 2.3 V.

GP2Y0A21YK0F Output Characteristics
Distance measuring characteristics (output)

The graph also shows the drawback of these sensors, the response is non-linear. In other words, a big change in the output voltage does not always correspond to a big change in range. In order to determine the distance between the sensor and an object, you need to find a function that converts the output voltage into a range value.

This can be done using MS Excel and results in the following formula for distances > 10cm:

Distance (cm) = 29.988 X POW(Volt , -1.173)

This is the function that is used in the SharpIR library, which we will be using later. Note that this function is based on data from the SHARP datasheet only. The output characteristics of the sensor will vary slightly from sensor to sensor so you might get inaccurate readings.

If you want to improve the accuracy of your readings, you can try to measure and plot many data points in Excel and fit a curve through these points. Once you have a new function for your specific sensor, you will need to change the formula used in the SharpIR.cpp file.

GP2Y0A21YK0F Specifications

Operating voltage4.5 to 5.5 V
Operating current30 mA
Measuring range10 to 80 cm
Output typeAnalog
Dimensions29.5 x 13 x 13.5 mm
Mounting holes2x 3.2 mm, 37 mm spacing
CostCheck price

For more information you can check out the datasheet here.


Wiring – Connecting GP2Y0A21YK0F IR sensor to Arduino

The wiring diagram below shows you how to connect the GP2Y0A21YK0F IR distance sensor to an Arduino.

SHARP GP2Y0A21YK0 with Arduino Wiring Diagram
GP2Y0A21YK0F IR distance sensor with Arduino​ wiring diagram.

These type of distance sensors tend to be a bit noisy, so it is recommended to add a capacitor between Vcc and GND. The datasheet suggests a capacitor of 10 µF or more (I used 220 µF). Connect the positive lead of the capacitor to the Vcc wire connection and the negative lead to the GND wire connection (see picture). Capacitors are often marked with a stripe which indicates the negative lead. The positive lead is often longer then the negative lead.

GP2Y0A21YK0F Connections

GP2Y0A21YK0FArduino
1 (Yellow)A0
2 (Black)GND
3 (Red)5V

If your sensor comes with different colored wires, be sure to check the pinout below. The Vo pin is connected to the analog in of the Arduino (A0).

SHARP GP2Y0A21YK0F Pinout
GP2Y0A21YK0F SHARP IR distance sensor pinout

Now that you have wired up the sensor it is time to look at some example code.


Installing the SharpIR Arduino library

The SharpIR library written by Guillaume Rico and Thibaut Mauon makes working with SHARP IR sensors a lot easier. It includes the formulas that are needed to convert the measured output voltage to a distance in centimeters. Currently, the library supports the following sensors: GP2Y0A02YK0F, GP2Y0A21YK0F, GP2Y0A710K0F, and GP2YA41SK0F. The latest version of the library can be downloaded here on GitHub or click the button below.

You can install the library by going to Sketch > Include Library > Add .ZIP Library in the Arduino IDE.

Installing an Arduino library ZIP
Installing a .ZIP Arduino library.

The author of the library noticed that the readings from the sensor can fluctuate quite a bit. The library solves this problem by taking multiple readings in a row, discarding outliers, and taking the mean to get a more stable distance reading. Currently, the library takes the mean of 25 readings which takes roughly 53 ms.


Example code for SHARP GP2Y0A21YK0F IR distance sensor with Arduino

The example code below can be used with the GP2Y0A21YK0F sensor and displays the measured distance in centimeters in the serial monitor.

You can copy the code by clicking the button in the top right corner of the code field.

/*SHARP GP2Y0A21YK0F IR distance sensor with Arduino and SharpIR library example code. More info: https://www.makerguides.com */

// Include the library:
#include <SharpIR.h>

// Define model and input pin:
#define IRPin A0
#define model 1080

// Create variable to store the distance:
int distance_cm;

/* Model :
  GP2Y0A02YK0F --> 20150
  GP2Y0A21YK0F --> 1080
  GP2Y0A710K0F --> 100500
  GP2YA41SK0F --> 430
*/

// Create a new instance of the SharpIR class:
SharpIR mySensor = SharpIR(IRPin, model);

void setup() {
  // Begin serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Get a distance measurement and store it as distance_cm:
  distance_cm = mySensor.distance();

  // Print the measured distance to the serial monitor:
  Serial.print("Mean distance: ");
  Serial.print(distance_cm);
  Serial.println(" cm");

  delay(1000);
}

Note that we have called the sensor ‘mySensor’ in this example. If you want to use multiple IR distance sensors, you can create another sensor object with a different name: SharpIR mySensor2 = SharpIR(IRPin2, model); Note that in that case you also use a different input pin for the second sensor.

You should get the following output in the serial monitor (Ctrl + Shift +M):

SHARP GP2Y0A21YK0F serial monitor output
Serial monitor output

Conclusion

n this article I have shown you how the SHARP GP2Y0A21YK0F IR distance sensor works and how you can use it with Arduino. I hope you found it useful and informative. If you did, please share it with a friend that also likes electronics!

I would love to know what projects you plan on building (or have already built) with this IR distance sensor. If you have any questions, suggestions, or if you think that things are missing in this tutorial, please leave a comment down below.

Note that comments are held for moderation to prevent spam.

12 thoughts on “How to use a SHARP GP2Y0A21YK0F IR Distance Sensor with Arduino”

  1. Hi
    Thanks for great guide, any chance you could explain how did you came up with this formula ?
    Distance (cm) = 29.988 X POW(Volt , -1.173)
    specially where 29.988 is coming from ?
    Thank you

  2. Hi, does anyone know how i could change the codes to get the median value of the 25 readings? Because currently they are finding the mean

  3. Hi,

    First thanks for sharing this amazing post!

    Would you be able to tell how much the length of the cable negatively affects the experiment? I have researched the literature and found only information about possible interference from other cables.
    I am asking because I plan to place a 30-40cm cable between the arduino plate and the sensor.

    Joao

    1. Benne de Bakker

      Hi Joao,

      I don’t think a 30-40 cm cable is going to be a big problem. One piece of advice is to keep them away from power cables going to motors etc. which can cause interference. If you are worried about this, you can also use a shielded cable and connect one side of the shield to earth.

      Benne

  4. Alexander Smith

    I am also getting this error code:

    exit status 1
    ‘distance_cm’ was not declared in this scope

    I have downloaded the .ZIP file from this exact post you made. Any fixes? Am I supposed to input something in this line?

    1. Benne de Bakker

      It sounds like the variable distance_cm was not declared before the loop section of the code. Did you copy the code from this article completely? In the example, the variable ‘distance_cm’ is created on line 11.

  5. Arduino: 1.8.9 (Windows 7), Board: “Arduino/Genuino Uno”

    Build options changed, rebuilding all
    C:\Projects\0ThumbDrive\ArduinoSketch\IRDistance\IRDistance.ino: In function ‘void loop()’:

    IRDistance:23:26: error: ‘class SharpIR’ has no member named ‘distance’

    distance_cm = mySensor.distance();

    ^

    exit status 1
    ‘class SharpIR’ has no member named ‘distance’

    I got this error when I compiled it. Any Ideas what it could be?

    1. Hi Anthony,

      Most likely you have a different library installed than the one I used. I know of at least 2 libraries that have the same ‘SharpIR.h’ name, so make sure you download and install the one that I linked in this tutorial. You will have to remove the one that you are currently using (go to Documents/Arduino/libraries on Windows and remove the SharpIR library folder).

      The library I used: https://github.com/guillaume-rico/SharpIR
      Other SharpIR library: https://github.com/qub1750ul/Arduino_SharpIR (available through Arduino library manager, search for ‘SharpIR’ to see if you have this one installed).

      I just installed the other library via the library manager and I got the same error, this library uses the function getDistance() instead of distance().

      Let me know if this solved the error.

      Benne

    1. Benne de Bakker

      Hi,

      I just retested the code and it seemed to run fine. Make sure you have the correct library installed and that you copy the entire code before modifying it.

      Benne

Comments are closed.