Infrared (IR) Sensor

In this project, you'll learn how to use an infrared (IR) sensor to either detect an object, or to distinguish between a black and a white color object.

The IR sensor can be used by a robot to avoid hitting a wall when it is configured for object detection, or used in a line tracing robot to follow either a black or white line on the floor when it is configured for black/white color detection.

Parts needed:
  • Arduino
  • An infrared (IR) sensor
  • Wires
IR sensor     
1 In order for the IR sensor to work correctly, you will first need to calibrate it. First, identify the signal LED that can be turned on and off by turning the potentiometer. This is the signal LED used in the calibration and detection below.

Calibration for object detection:
  • The IR sensor can detect an object that is less than about 9 inches away.
  • Point the IR sensor to a wall that is about 2 feet away.
  • Turn the potentiometer fully clockwise.
  • Slowly turn the potentiometer counterclockwise until the signal LED just turns off.
  • The signal LED will turn on when an object is placed less than about 9 inches away.
Calibration for black/white color detection:
  • Mount the IR sensor about 1 to 2 inches above a black surface.
  • Turn the potentiometer fully clockwise.
  • Slowly turn the potentiometer counterclockwise until the signal LED just turns off.
  • Do not change the distance between the IR sensor and the black surface. If you need to change the distance then you need to re-calibrate.
  • The signal LED will turn on when the sensor is above a white surface and off when it is above a black surface.
2 Making the connections
  • Connect VCC on the IR sensor to 5V on the Arduino.
  • Connect GND on the IR sensor to GND on the Arduino.
  • Connect OUT on the IR sensor to pin 2 on the Arduino.
3 Create a new program and type in this program.


The OUT pin from the IR sensor outputs a LOW value when it receives a reflected IR signal, i.e. detected an object (white), and a HIGH value when it is not receiving a reflected IR signal, i.e. no object (black).

Both the signal LED on the IR sensor and the built-in led on the Arduino is turned on when it detects an object (white) and off when there is no object (black).

The ! symbol inverts the value from HIGH to LOW or from LOW to HIGH
void setup() {
  pinMode(13, OUTPUT);  // internal LED
  pinMode(2, INPUT);    // IR input
}

void loop() {
  int v = digitalRead(2);
  digitalWrite(13, !v);	// the ! symbol inverts the value
  delay(50);
}