One-sentence summary
Obstacle detection is the decision logic that lets a robot measure the distance to the object in front of it with a sensor and then stop or change direction when that distance drops below a threshold we choose.
Why does it matter?
In the previous lesson we saw how motors turn and how a motor driver powers them. But a robot that only moves does not see the wall in front of it; it runs straight into it. A real robot also senses its surroundings and decides what to do.
This lesson joins three parts you already learned separately:
- Sense: The sensor measures distance.
- Decide: The program compares the distance to a threshold.
- Act: The motor driver stops or turns the robot.
This is called the sense–decide–act loop, the foundation of almost every robot. A robot vacuum turning before it hits a table, a parking sensor beeping, a drone slowing near the ground — all the same idea.
How do we "see" an obstacle?
A robot does not see with eyes. Instead we use sensors that turn distance into a number. Two common choices exist.
Ultrasonic sensor (HC-SR04)
This sensor sends out a sound wave too high-pitched for us to hear. The sound hits an obstacle and bounces back; the sensor measures how long the round trip takes.
Think of shouting in a cave and waiting for the echo. A quick echo means the wall is close; a slow one means it is far. Sound travels through air at about 340 metres per second, so if we know the time, we can work out the distance.
- We send a short pulse to the Trig pin; the sensor emits the sound.
- The Echo pin stays HIGH until the echo returns.
- The length of that time tells us the distance.
An ultrasonic sensor measures well from about 2 cm up to roughly 4 metres, and it does not care about colour.
Infrared (IR) sensor
An infrared sensor sends out light we cannot see and measures how much bounces back. It detects nearby obstacles quickly, but its range is shorter and it can be affected by the object's colour and by sunlight. A black surface absorbs the light, so it is harder to detect.
Simple rule: If you want to measure farther and ignore colour, use ultrasonic; if you want a fast, close-range "there / not there" answer, infrared is often better.
The threshold: "How close is too close?"
The robot measures a distance, say 42 centimetres. Is that dangerous? We are the ones who tell the robot. The limit we set is called the threshold.
Think of the threshold as a safety circle: an invisible ring around the robot, and when an object enters it, the robot reacts.
Example: Threshold = 15 cm.
- Measured distance is 40 cm: the way is clear, keep moving.
- Measured distance is 12 cm: the obstacle is too close, stop.
Too small a threshold and the robot may not stop before hitting the obstacle. Too large and it is scared of everything and never moves. We find the right value by testing, based on the robot's speed and size.
The decision logic: pseudocode first
Before writing code, writing the logic as pseudocode — close to everyday language — helps us see the solution clearly.
Repeat (forever):
distance = read distance from sensor
If distance < 15 centimetres
stop the motors
reverse for a short moment
turn right
Otherwise
move forward
This logic is really a mix of the three building blocks you already know: a continuous loop (repeat), a condition (if), and sequential commands. Robotics connects these familiar ideas to the physical world.
The same logic in Arduino
Now let us write the same idea in real Arduino (C++) code. We use a small helper function that reads the distance in centimetres from the ultrasonic sensor.
const int trigPin = 9;
const int echoPin = 10;
const int threshold = 15; // threshold in centimetres
long readDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // send the sound wave
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long time = pulseIn(echoPin, HIGH); // measure echo time
return time * 0.034 / 2; // convert time to distance
}
Because the sound travels out and back, we divide the total time by two; 0.034 is how far sound travels in one microsecond (in centimetres).
In the main loop we compare that distance to the threshold:
void loop() {
long distance = readDistance();
if (distance < threshold) {
stop(); // stop both motors
delay(200);
reverse(300); // back up briefly
turnRight(400); // look for a new direction
} else {
goForward(); // keep going if the way is clear
}
}
Functions like stop(), goForward() and turnRight() are filled in with the motor-driver commands from the previous lesson. That is how the two lessons connect: the sensor decides, the driver acts.
Cleaning up noise: the idea of filtering
Sensors are not perfect. An ultrasonic sensor can sometimes give a single wrong reading; for example, it suddenly says "3 cm" while the path is actually clear. If we trust that one bad reading and stop the robot, the robot seems to twitch for no reason.
The idea that fixes this is filtering: instead of trusting one reading, we look at several together.
One simple method is to take a few measurements in a row and use the middle one (or the average):
take three measurements
throw away the strange, extreme value
decide based on the ones that remain
Another simple rule: stop only if two readings in a row are below the threshold, so a single wrong reading cannot ruin the decision. Filtering is a small but important habit that makes real robots far steadier and more reliable.
Mini practice
Design a paper "corridor test." You do not need to write code; the goal is to build the logic.
- Choose a threshold for your robot (for example 20 cm). Write one sentence explaining why you chose that value.
- Write what the robot should do in each of these three cases:
- Measured distance is 55 cm.
- Measured distance is 18 cm.
- The sensor reads "2 cm" once, then immediately "60 cm", then "58 cm" again.
- Explain, using the idea of filtering, why the robot should not stop immediately in the third case.
Hint: In the third case, the single "2 cm" is most likely a wrong reading.
Common mistakes
Forgetting to connect a common ground (GND)
If the sensor and the Arduino do not share the same GND line, the measurements come out meaningless. A common reference is essential for the signals to be measured correctly.
Choosing the wrong threshold
If the threshold is smaller than the robot's stopping distance, there is no room to stop by the time the robot notices. Remember that a faster robot has to decide earlier.
Trusting a single reading
Deciding from one measurement without filtering makes the robot jittery and unpredictable. Look at more than one reading.
Mounting the sensor facing the wrong way
If the sensor points slightly up, it misses low obstacles; if it points too far down, it treats the floor as an "obstacle." Mount the sensor parallel to the ground with a clear view ahead.
Safety note
A moving robot can fall, pinch a finger or hair, and run into things around it. Before you test, keep these in mind:
- Clear a safe area. Test on a wide, empty floor away from the edge of a table; the robot can fall off an edge.
- Keep hands, hair and cables away from wheels and gears. Spinning parts can pinch.
- Test at low speed first. Start the robot slowly on its first run; once the logic is right, increase the speed later.
- Use a motor driver and a separate low-voltage battery. Do not power the motors straight from an Arduino pin; the motors should draw power from a separate battery pack through the driver. Connect the ground (GND) of the Arduino and the battery together (a common ground).
- Never use mains electricity (the wall socket). Only low-voltage battery packs.
- Have an adult nearby when working with motors and tools.
Lesson summary
- Obstacle detection is the logic that compares a sensor-measured distance to a threshold and decides what to do.
- An ultrasonic sensor measures distance with a sound echo; an infrared sensor uses reflected light.
- The threshold sets how close the robot reacts; we choose it based on the robot's speed and size.
- The decision logic is the sense–decide–act loop: the sensor reads, the program compares to the threshold, the motor driver carries out the movement.
- Filtering looks at several readings so that one wrong measurement cannot fool the robot.
Check questions
- How does an ultrasonic sensor measure distance?
- What does "threshold" mean, and why do we set it for the robot?
- If the measured distance is greater than the threshold, what should the robot do?
- Why is filtering needed? Give an example.
- Why should we power the motors from a separate battery and motor driver instead of directly from an Arduino pin?
Answers
- It sends out a high-pitched sound wave we cannot hear; the sound hits an obstacle and bounces back, and the sensor measures the round-trip time. We multiply the time by the speed of sound and divide by two to find the distance.
- The threshold is the boundary distance at which the robot reacts. The robot does not know what "close" means by itself; we set it based on the robot's speed and size.
- It means the way is clear, so the robot keeps moving forward.
- Sensors sometimes give a one-off wrong reading. If we trust a single reading, the robot stops or twitches for no reason. For example, a single "2 cm" on a clear path can be ignored once we look at several readings together.
- Motors draw more current than an Arduino pin can supply and could damage the board. A separate battery pack powers the motors, the motor driver controls that power, and the Arduino only sends commands. The GND is connected in common.
Source and verification note
For “Obstacle Detection”, verification focuses on whether the relationship between How do we "see" an obstacle? and Infrared (IR) sensor remains consistent across examples. Robot behaviour cannot be explained by code alone; mechanical structure, power system, sensor placement and surface conditions must be evaluated together. Test results should be recorded over several runs on the same course.
Next lesson
Line Following: The robot follows a line on the ground with its sensors and travels a route on its own.