Skip to content

Infrared sensor

Slides

F for fullscreen · O for overview

What is infrared sensor?

Infrared sensors on the turtle robot
Infrared sensors connection

How does infrared sensor work?

Infrared sensors come in pairs of a transmitter and a receiver. The transmitter emits infrared wave/light, and the receiver will receive the infrared wave if the infrared wave is reflected by the surface. If the infrared wave is not reflected by the surface, the receiver will not receive any infrared wave. This is normally used to detect if the surface is white (LOW) or black/dark (HIGH) in colour.

Reading from infrared sensors

Pin mode definition

Purpose Mode Pin on board
Left sensor Input 6
Middle sensor Input 7
Right sensor Input 8

Light up LED to reflect the state of left sensor

int sensor1 = 6; //(1)
int ledPin = 11; //(2)
void setup() {
  pinMode(sensor1, INPUT); //(3)
  pinMode(ledPin, OUTPUT); //(4)
}

void loop() {
  if (digitalRead(sensor1) == LOW) {  //(5)
    digitalWrite(ledPin, HIGH);  //(6)
  } else {
    digitalWrite(ledPin, LOW); //(7)
  }
}
  1. Define the pin of left sensor as pin D6
  2. Define LEDpin as Digital 11
  3. Define the sensor as INPUT
  4. Define LED as OUTPUT
  5. Read the state of sensor, if detect the white paper, it is at LOW level
  6. Light the LED
  7. Turn off the LED

Light up LED to reflect the state of middle sensor

int sensor2 = 7; //(1)
int ledPin = 11; //(2)
void setup() {
  pinMode(sensor2, INPUT); //(3)
  pinMode(ledPin, OUTPUT); //(4)
}

void loop() {
  if (digitalRead(sensor2) == LOW) {  //(5)
    digitalWrite(ledPin, HIGH);  //(6)
  } else {
    digitalWrite(ledPin, LOW); //(7)
  }
}
  1. Define the pin of middle sensor as pin D7
  2. Define LEDpin as Digital 11
  3. Define the sensor as INPUT
  4. Define LED as OUTPUT
  5. Read the state of sensor, if detect the white paper, it is at LOW level
  6. Light the LED
  7. Turn off the LED

Light up LED to reflect the state of right sensor

int sensor3 = 8; //(1)
int ledPin = 11; //(2)
void setup() {
  pinMode(sensor3, INPUT); //(3)
  pinMode(ledPin, OUTPUT); //(4)
}

void loop() {
  if (digitalRead(sensor3) == LOW) {  //(5)
    digitalWrite(ledPin, HIGH);  //(6)
  } else {
    digitalWrite(ledPin, LOW); //(7)
  }
}
  1. Define the pin of right sensor as pin D8
  2. Define LEDpin as Digital 11
  3. Define the sensor as INPUT
  4. Define LED as OUTPUT
  5. Read the state of sensor, if detect the white paper, it is at LOW level
  6. Light the LED
  7. Turn off the LED

Bring it further

  1. How do we detect if the robot stays at the middle of a black line on a white background? How about the robot is slightly to the left or right of the black line?