Site icon AranaCorp

Using a distance sensor GP2Y0A21 with Arduino

infrared sensor scheme

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.

Hardware

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.

diagram

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.

Code

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:

//Parameters
const int gp2y0a21Pin  = A0;

//Variables
int gp2y0a21Val  = 0;

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

void loop() {
  testGP2Y0A21();
}

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;
}


Applications

Sources

Find other examples and tutorials in our Automatic code generator
Code Architect

Exit mobile version