IR Range Finder

Sharp GP2D02 & GP2D12
Sharp GP2D02 & GP2D12

A reliable way to measure short distances would be with the Sharp Infrared Range Finders. These Infrared sensors are inexpensive, relatively accurate and quite easy to use. In this overview, we will look at the Sharp GP2D12 & GP2D02 sensors.

The GP2D12 & GP2D02 can detect distances that are around 4″ to 30″ away from the sensor. The Infrared Range Finders calculate the sensor-object distance through the process of triangulation. Triangulation works by detecting the reflected Infrared beam angle, and by discovery of the angle – the distance can then be determined. In practice, the Infrared Range Finder emits a pulse of Infrared light, which is then reflected back by the target object or not. The Infrared Range Finder receiver allows the reflected infrared light to fall onto an enclosed linear CCD array. The CCD array then determines the angle, and computes a corresponding value which is sent to your microcontroller.

The Infrared Range Finders, GP2D12 & GP2D02, have a non-linear output. As the distance measured from the sensor may increase or decrease linearly, the output from the sensor may increase or decrease non-linearly. This occurs when the Infrared Range Finders are not capable of detecting very short distances – less than 4″ from the sensor. Check the datasheet of the Infrared Range Finder to determine the minimum and maximum distances supported.

Even though the GP2D12 & GP2D02 are similar in terms of functional use, these two sensors differ in the manner in which the sensed-distance is communicated to your microcontroller. The simplest of the two, the GP2D12, simply outputs the sensed-distance as an analog voltage, whereas the GP2D02 outputs the sensed-distance as a byte-value.

The GP2D12 & GP2D02 are easily hooked up to the Arduino, as seen below:

GP2D12 & Arduino
GP2D12 & Arduino

Arduino code for the GP2D12:

int IR_SENSOR = 0; 
int irVal = 0; 

void setup() 
{
     Serial.begin(9600); 
}

void loop() 
{
  // read the value from the ir sensor
  irVal = analogRead(IR_SENSOR);    
  Serial.println(irVal);
  delay(100);
}
GP2D02 & Arduino
GP2D02 & Arduino
GP2D02 Timing Chart
GP2D02 Timing Chart

Arduino code for the GP2D02:

int IR_VIN = 2;
int IR_VOUT = 3;

void setup()
{
  pinMode(IR_VIN, OUTPUT);
  pinMode(IR_VOUT, INPUT);
  Serial.begin(9600);
}

void loop()
{  
  int range = getGP2D02_Range(); 
  Serial.print(range);
  Serial.println("");
  delay(25);
}

int getGP2D02_Range()
{
  int val = 0;

  digitalWrite(IR_VIN, LOW);
  delay(70);
   
  for(int i = 7; i >= 0; i--)
  {
    digitalWrite(IR_VIN, HIGH);
    delayMicroseconds(100);  
    digitalWrite(IR_VIN, LOW);
    delayMicroseconds(100);
    
    val |= (digitalRead(IR_VOUT) << i);
    //Serial.print(digitalRead(IR_VOUT));
   }

   digitalWrite(IR_VIN, HIGH);
   delay(2);
   digitalWrite(IR_VIN, LOW);
  return val;
}