Education › Robotics › Stage 2: Sense and move

Sensors: giving a robot senses

Ultrasonic, infrared, IMU, encoders and cameras — how they work and how to read them reliably.

Beginner→Intermediate ~34 min read Module 6 of 16

Sensors are how a robot perceives the world — without them it is a machine moving blind. This lesson covers the sensors you will actually use first: ultrasonic and infrared for distance and lines, the IMU for orientation, and encoders for measuring wheel rotation. You will learn how each works, how to read it in code, and why every real sensor is noisy and what to do about it. Good sensing is the foundation of every behaviour you will build.

After this module you can
  • Choose the right sensor for a task: distance, line, orientation or rotation
  • Read an ultrasonic and an infrared sensor in code
  • Understand what an IMU and a wheel encoder measure
  • Recognise sensor noise and apply a simple filter or threshold

Distance: ultrasonic and infrared

The two cheap ways to measure distance are ultrasonic and infrared, and they fail differently. An ultrasonic sensor (the HC-SR04 in every kit) sends a burst of sound and times the echo; distance is half the round-trip time multiplied by the speed of sound. It works from a few centimetres to a couple of metres, is cheap and reliable, but has a wide beam (it sees a cone, not a point) and struggles with soft or angled surfaces that scatter the echo. An infrared distance sensor shines IR light and measures the reflection; it is faster and narrower but shorter-range and fooled by surface colour and sunlight.

You read the HC-SR04 by sending a short trigger pulse and timing how long the echo pin stays high. pulseIn does the timing for you; divide by the round-trip factor to get centimetres.

cpp
// Read distance in cm from an HC-SR04 ultrasonic sensor.
const int TRIG = 9, ECHO = 10;

void setup() {
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600);
}

long readCm() {
  digitalWrite(TRIG, LOW); delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);  // 10us trigger burst
  digitalWrite(TRIG, LOW);
  long us = pulseIn(ECHO, HIGH, 30000);  // echo time, timeout 30ms
  return us / 58;                         // us to centimetres
}

void loop() {
  Serial.println(readCm());
  delay(60);  // small gap so echoes don't overlap
}

Lines and edges: infrared reflectance

A line sensor is a small IR emitter and detector pointed at the ground. A black line absorbs IR and reflects little; a white surface reflects a lot. The sensor gives a digital HIGH/LOW (past a built-in threshold) or an analog value you threshold yourself. An array of two or more line sensors under the front of a robot is all you need to follow a line: if the left sensor sees black and the right sees white, steer left, and vice versa. The same reflectance idea, pointed forward, makes a cheap short-range obstacle detector.

Tip

Line sensors are sensitive to height and ambient light. Mount them a few millimetres above the surface, and calibrate the black/white threshold in the actual room you will run in — a value tuned under office lights can fail in daylight.

Orientation: the IMU

An IMU (inertial measurement unit, like the MPU-6050) combines an accelerometer and a gyroscope, usually read over the I2C bus. The accelerometer measures acceleration including gravity, so at rest it tells you which way is down — useful for tilt. The gyroscope measures rotational speed, so integrating it tells you how much the robot has turned. Neither is perfect alone: the accelerometer is noisy under motion, and the gyro drifts over time. Combining them (sensor fusion, often a complementary or Kalman filter) gives a stable orientation, which is how balancing robots and drones know their attitude.

For a first robot you rarely need full fusion — a gyro read to detect 'have I turned 90 degrees yet' is often enough. Know that the IMU exists and what each part measures; reach for fusion when you build something that must stay upright.

Rotation: wheel encoders

An encoder counts how far a wheel has turned. A simple version is a slotted disc on the axle and an IR sensor that pulses once per slot; counting pulses tells you rotation, and rotation times wheel circumference tells you distance travelled. Encoders are what turn 'drive forward' into 'drive forward exactly 30 cm' and are essential for accurate movement, odometry (estimating position from wheel motion), and closed-loop speed control. Without them, a robot commanded to go straight drifts, because no two motors are identical.

Encoders produce pulses that can come fast, so they are usually read with interrupts — a function that fires on each pulse and increments a counter — rather than polling in the loop, so none are missed. Even a cheap encoder transforms how precisely a robot can move.

Every sensor is noisy

Real sensors do not give clean numbers. An ultrasonic reading occasionally spikes to a wrong value; an analog line sensor jitters; an IMU is noisy under vibration. If your robot reacts to every raw reading, it will twitch and misbehave. Two simple defences handle most of it: thresholding with hysteresis (act only when a value clearly crosses a level, and require it to cross back by a margin before reversing, so it does not chatter at the boundary), and averaging or a running filter (average several readings, or a simple exponential filter, to smooth jitter). A median of three readings also kills isolated spikes cheaply.

Note

The rule: never trust a single reading for an important decision. Smooth it, threshold it with margin, or take a few readings and use the median. This one habit removes most 'why is my robot twitching' problems.

Hands-on practice

Read and smooth a distance sensor

  1. Wire an HC-SR04 and print its distance to the Serial Monitor once per loop.
  2. Wave your hand at it and watch for occasional spike readings among the good ones.
  3. Take three readings and use their median instead of one, and confirm the spikes disappear.
  4. Add a threshold with hysteresis: light an LED when closer than 15 cm, turn it off only above 20 cm.
  5. Add a line sensor over black and white surfaces, read its value, and pick a threshold that separates them reliably in your room.
Cheat sheet

Sensors: giving a robot senses — at a glance

Main things to focus on

  • Ultrasonic times an echo; wide beam, good for general distance.
  • Infrared reflectance reads lines and short-range obstacles by how much light bounces back.
  • An IMU gives tilt (accelerometer) and turn rate (gyroscope); fuse them for stable orientation.
  • Encoders count wheel rotation for accurate distance and odometry.
  • Read fast pulses (encoders) with interrupts, not polling.
  • Never trust one reading — threshold with hysteresis, or take a median/average.

Distance & lines

HC-SR04ultrasonic distance; trigger + echo timing
pulseIn(echo, HIGH)times the echo pulse in microseconds
us / 58converts echo time to centimetres
IR line sensorblack absorbs, white reflects; digital or analog

Orientation

Accelerometermeasures acceleration incl. gravity → tilt
Gyroscopemeasures turn rate; integrate for angle (drifts)
IMU (MPU-6050)accel + gyro over I2C
Sensor fusioncombine accel + gyro for stable attitude

Rotation

Encodercounts wheel rotation via slotted disc + IR
Interruptfires on each pulse so none are missed
Odometryestimate position from wheel rotation
pulses × circumferenceconverts counts to distance travelled

Cleaning noise

Median of 3kills isolated spike readings cheaply
Hysteresiscross by a margin before reversing a decision
Running averagesmooths jitter over several readings

Common pitfalls

  • Trusting a single ultrasonic reading, which occasionally spikes to a wrong value.
  • Setting a line-sensor threshold under different light than the robot will run in.
  • Polling a fast encoder in the loop and missing pulses instead of using interrupts.
  • Expecting the accelerometer to give a clean heading — it is noisy under motion and needs fusion.
  • Reacting to raw noisy values, so the robot twitches at decision boundaries.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →