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.
- 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.
// 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.
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.
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.