Build a mini robotBeginnerLesson 2657 min read

Sensors: how a robot notices the world

Line sensors see dark and light, ultrasonic sensors measure distance with sound, and every sensor is a bit noisy. Learn what each one really tells you.

Lesson in motion

In 60 seconds

Sensors: how a robot notices the world

Line sensors see dark and light, ultrasonic sensors measure distance with sound, and every sensor is a bit noisy. Learn what each one really tells you.

1/3
In simple words
Close your eyes and walk slowly towards a wall with your hands out. Your fingers tell you "wall!" just in time. A bat does something cleverer: it makes a squeak and listens for the echo. The quicker the echo comes back, the closer the wall. Robots use both tricks: sensors that feel what is right under them, and sensors that measure distance with sound.
A sensor turns something in the world, like light, sound or pressure, into a number your code can read. A robot only knows what its sensors tell it. If the sensors are wrong or blind in some place, the robot is too.

Infrared (IR) line sensors

A small IR line sensor has a tiny light that shines invisible infrared light down at the floor, and a detector next to it. A white or light floor reflects a lot of light back. Black tape reflects much less. The module turns this into a signal: "light" or "dark". Put two of them side by side at the front of the robot, and it can tell if the tape is under the left sensor, the right sensor or both.
  • They work best very close to the floor, usually a few millimetres to about a centimetre. Check your module's datasheet.
  • Many modules have a small screw (a potentiometer) to set the light/dark threshold. Adjust it on your real floor.
  • Sunlight also contains infrared light and can confuse them. Test in the room where the robot will run.
  • Some modules give HIGH on black and LOW on white, others the opposite. Always test and print the reading first.

Ultrasonic distance sensors

A common ultrasonic sensor, the HC-SR04, has two round "eyes": one sends a short burst of sound too high for us to hear, the other listens for the echo. The board measures how long the echo took. Sound travels about 343 metres per second in air at room temperature, which is about 0.0343 cm per microsecond. The sound goes there and back, so:
Python: from echo time to distancepython
SPEED_OF_SOUND = 0.0343          # cm per microsecond, in air at about 20 °C

def echo_to_cm(echo_microseconds):
    return echo_microseconds * SPEED_OF_SOUND / 2   # divide by 2: there and back

for us in [580, 1166, 2915, 5830]:
    print(f"echo took {us:5} microseconds  ->  about {echo_to_cm(us):5.1f} cm")
  • It sees in a cone, not a thin line. Our virtual sensor copies this with three rays.
  • Soft things (cloth, a sofa) absorb sound and may give no echo. A wall at a sharp angle can bounce the sound away, so the sensor "sees" nothing.
  • Very close objects, closer than a few centimetres, are often not measured correctly.

Every sensor is noisy

Real readings jump around. A distance sensor pointed at a still wall might say 40, 41, 39, 40, then suddenly 250 because one echo was missed. If your robot believes that one bad number, it may speed up into the wall. A simple fix is to keep the last few readings and use the median (the middle value when sorted). One wild reading cannot move the median much.
Python: a median filter removes a wild readingpython
import numpy as np

rng = np.random.default_rng(7)
true_cm = np.linspace(80, 20, 30)                  # robot drives towards a wall
readings = true_cm + rng.normal(0, 1.5, 30)        # small noise
readings[[9, 20]] = [250, 3]                       # two wild readings (missed echo, glitch)

def median3(values, i):
    return float(np.median(values[max(0, i - 2): i + 1]))

for i in range(6, 24, 2):
    print(f"true {true_cm[i]:5.1f}   raw {readings[i]:6.1f}   median of last 3 {median3(readings, i):6.1f}")
SensorWhat it tells youCommon trouble
IR line sensorIs the floor under me dark or light?Sunlight, shiny floors, wrong height or threshold
Ultrasonic (HC-SR04)How far is the nearest thing ahead, roughly?Soft or angled surfaces, very close objects, missed echoes
Wheel encoderHow far has each wheel turned?Wheel slip means the robot did not really move that far
Bump switchDid I touch something?Only tells you after the touch
Watch out
A sensor that is silent is not the same as "nothing there". Many ultrasonic codes return 0 or a large number when no echo comes back. Decide on purpose what your robot does then. A cautious robot slows down when it is unsure.
Try this. In the median code, change the wild reading at index 20 to 150. Does the median still hide it? What if two wild readings come one after the other?

Watch and read more

Lab

A decide function that uses the distance sensor to slow down and stop 10–30 cm from a wall, from any starting point.

~20 min

The problem

This runs in your browser. The robot faces a wall at the right side of the room. s["distance"] is the distance in cm from the middle of the robot to the nearest thing ahead (at most 100).

  1. Run the starter. The robot crashes into the wall.
  2. Change decide so the robot drives forward, slows down as the wall gets close, and stops with its middle 10–30 cm from the wall.
  3. It must work from different starting points, so use the sensor, not a step count. The check also tries a start you cannot see.
  4. Tip: a smooth rule is speed = (distance − 20) / 40, kept between 0 and 1 with np.clip. Explain in one sentence why slowing down is safer than stopping suddenly on a real robot.

Practice lab

Edit the code and run it. Python runs in your browser — nothing is sent to our server.

Output

No output. Add print(...) to see values.

You are done when

Hard questions

Try to answer before you reveal. If you can answer these, you understood the lesson.

Q1Your robot stops at 20 cm in the simulator. On the real robot it bumps the wall. Give two likely reasons.Reveal

First, a real robot does not stop instantly: it rolls on a little after the motors stop, more on a smooth floor or with a heavy battery. Second, the real sensor reads less often and can miss an echo, so the code may react late. Also, the real sensor measures from the front of the robot, not the middle. Slow down earlier and add a safety margin.

Q2Why might a robot that uses only one ultrasonic sensor still hit a chair leg?Reveal

The sensor sees in a cone straight ahead, and thin, round objects reflect little sound. A chair leg can be outside the cone when the robot turns, or too thin to give a clear echo. Real robots combine sensors: a bump switch, side sensors or a camera.

Please sign in to continue.

Questions people ask

Why does my IR sensor work at home but not at school?

The floor, the tape and the light are different. A shiny floor, bright sunlight from a window or a different tape can change the reading. Adjust the threshold on the new floor and test again.

Can the ultrasonic sensor see a thin stick or a chair leg?

Sometimes not. Thin or round objects reflect only a little sound back. For those, robots add other sensors, such as bump switches or an IR distance sensor, or a camera.

Is the median always better than the average?

For rare wild readings, yes, it is usually better. But the median of the last few readings reacts a little later to real changes. Use a short window, such as 3 or 5 readings, so the robot still reacts in time.

Does temperature change the ultrasonic reading?

Yes, a little. Sound travels a bit faster in warm air than in cold air. For a small robot avoiding walls the difference usually does not matter; for careful measuring it can.

Lesson test

5 questions. Get 3 right (60%) to pass and complete this lesson.

Sign in to take the test and save your progress