Infrared distance sensors
What you’ll learn
- Three kinds of IR distance sensor and when to use each
- Strengths and weaknesses compared with ultrasonic
IR obstacle modules (digital)
An IR LED and receiver side by side. If enough IR reflects back, the output switches. A screw sets the trigger distance (usually a few cm up to about 30 cm). Cheap and fast, but only says “something is near”, not how far.
Sharp IR sensors (analog)
Sensors like the GP2Y0A21 measure distance by triangulation: the angle at which reflected light lands on a detector. They give an analog voltage for roughly 10–80 cm. The output is not linear and reads wrongly when closer than the minimum range, so use the datasheet’s curve or a lookup table.
Time-of-flight (ToF) laser sensors
Sensors like the VL53L0X time how long a laser pulse takes to return, much like ultrasonic but with light. They talk over I²C, give millimetres directly, have a narrow beam and work to about 1–2 m depending on the model.
IR versus ultrasonic
| Ultrasonic | IR / ToF | |
|---|---|---|
| Beam | Wide cone | Narrow |
| Soft materials | Poor | Fine |
| Black or shiny surfaces | Fine | Can be poor |
| Bright sunlight | Fine | Can be affected |
| Speed | ~20 readings/s | Faster |
Many robots use both: ultrasonic forwards for a wide view, IR or ToF on the sides for wall following.
Example: wall following with a side sensor
Keep 15 cm from the wall on the right:
function loop() { const d = distanceRight(); if (d < 12) motors(40, 60); // too close: steer left else if (d > 18) motors(60, 40); // too far: steer right else motors(60, 60); // just right}Example: reading a digital IR module
void setup() { pinMode(7, INPUT); Serial.begin(9600); }void loop() { // most modules pull the output LOW when they see an obstacle Serial.println(digitalRead(7) == LOW ? "obstacle" : "clear"); delay(100);}Try it
distanceLeft() and distanceRight() act like side-facing IR sensors.
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Tune the gapEasy
Change the target distance from the wall and watch how the robot’s path changes.
Reach the goalMedium
Improve the wall follower until it reaches the green goal.
When the wall on the right disappears (a gap), turn right gently, e.g. motors(60, 40), so the robot doesn’t clip the wall’s end.
Choose the sensorHard
A robot must detect a black chair leg 30 cm away in sunlight, and a curtain 1 m away. Which sensors would you use? Ultrasonic for the curtain (IR handles soft material fine but ultrasonic has range and ignores sunlight), and ultrasonic or a ToF sensor for the chair leg. A simple IR module may miss black objects in sunlight.
Quick check
Finished this lesson?