IR line sensors
What you’ll learn
- How an infrared (IR) line sensor sees a line
- How to set one up and test it
- How two sensors steer a line-following robot
How it works
A line sensor (such as the common TCRT5000 module) has an IR LED and an IR receiver side by side, pointing at the floor.
- White or light floor: reflects lots of IR back.
- Black line: absorbs IR, so little comes back.
The module turns this into a signal. Most have an analog output (AO), a digital output (DO) and a small screw (potentiometer) that sets the digital threshold.
Setting up
- Mount it 2–10 mm above the floor (check the module’s datasheet; the TCRT5000 works best close).
- Turn the threshold screw until the on-board LED changes exactly at the line’s edge.
- Use a matte black line (electrical tape) on a light surface.
Two sensors steer
Place two sensors either side of the line:
| Left sensor | Right sensor | Meaning | Do |
|---|---|---|---|
| white | white | Line between the sensors | Go straight |
| black | white | Line drifting left | Turn left |
| white | black | Line drifting right | Turn right |
| black | black | Junction or end | Stop or decide |
Example: testing a sensor on an Arduino
void setup() { Serial.begin(9600); pinMode(7, INPUT); }void loop() { Serial.print("digital: "); Serial.print(digitalRead(7)); Serial.print(" analog: "); Serial.println(analogRead(A0)); delay(200);}Move it over white paper and black tape and note both readings.
Example: two-sensor logic in the simulator
function loop() { if (lineLeft() && lineRight()) motors(0, 0); // both see black: stop else if (lineLeft()) motors(10, 60); // turn left else if (lineRight()) motors(60, 10); // turn right else motors(50, 50); // straight}Try it
The virtual robot has two line sensors either side of the black line (they turn red when they see black).
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
Faster lapEasy
Raise the straight-line speed. What’s the fastest speed that still completes a lap?
Smoother turnsMedium
The robot zig-zags. Change the turn speeds so it turns less sharply but still holds the line.
Instead of motors(10, 60), try motors(30, 60) and motors(60, 30). Gentler turns zig-zag less, but at high speed they may not turn enough on curves.
Count the lapsHard
Print a message each time the robot passes its starting point.
Use millis(): a lap takes several seconds. Or count how many times both sensors leave and re-find the straight at the top.
Quick check
Finished this lesson?