Simple IR Distance Sensor Tutorial

Introduction

This tutorial explains how to make a simple IR distance sensor using a Panasonic pna4602m IR sensor and an IR led.

Hardware Requirments

  1. Panasonic pna4602m IR sensor (1)
  2. IR led (1)
  3. 220 ohm resistor (2)

Theory and circuits

For the theory behind this sensor, and for information about setting up the circuit see the boe bot instruction manual page 249. The circuit schematics are on page 252. http://parallax.com/Portals/0/Downloads/docs/books/edu/Roboticsv2_2.pdf

In a nutshell, you have to output a 38.5khZ square wave to the IR led for 1 millisecond, and then check the state of the sensor pin. If the pin is low, then an object is detected. Note that the schematic in the boe bot manual recommends a 1k resistor for the IR led. I chose to use a 220 ohm resistor. With a 220 ohm resistor, this sensor can detect my hand up to about 30cm(1 foot) away. If you use a higher value resistor, then the sensor has less range.

Arduino Code

//define pins. I used pins 4 and 5
#define irLedPin 4          // IR Led on this pin
#define irSensorPin 5       // IR sensor on this pin

int irRead(int readPin, int triggerPin); //function prototype

void setup()
{
  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  Serial.begin(9600); 
  // prints title with ending line break 
  Serial.println("Program Starting"); 
  // wait for the long string to be sent 
  delay(100); 
}

void loop()
{  
  Serial.println(irRead(irSensorPin, irLedPin)); //display the results
  delay(10); //wait for the string to be sent
}

/******************************************************************************
 * This function can be used with a panasonic pna4602m ir sensor
 * it returns a zero if something is detected by the sensor, and a 1 otherwise
 * The function bit bangs a 38.5khZ waveform to an IR led connected to the
 * triggerPin for 1 millisecond, and then reads the IR sensor pin to see if
 * the reflected IR has been detected
 ******************************************************************************/
int irRead(int readPin, int triggerPin)
{
  int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds
  int cycles = 38; //26 microseconds * 38 is more or less 1 millisecond
  int i;
  for (i=0; i <=cycles; i++)
  {
    digitalWrite(triggerPin, HIGH); 
    delayMicroseconds(halfPeriod);
    digitalWrite(triggerPin, LOW); 
    delayMicroseconds(halfPeriod - 1);     // - 1 to make up for digitaWrite overhead    
  }
  return digitalRead(readPin);
}

Share