Home · Academy · Robotics & Coding · Robotic Systems · Obstacle Detection

Obstacle Detection

Learn to detect an obstacle ahead with a distance sensor and stop or turn.

LESSON COMPASS

What will you use this page for?

Core idea

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.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

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…

Next connection

Line Following: The robot follows a line on the ground with its sensors and travels a route on its own.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration30–45 min
PrerequisiteMotors and Drivers
ContentStandard lesson · 1,736 words
Last updated

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:

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.

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.

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.

  1. Choose a threshold for your robot (for example 20 cm). Write one sentence explaining why you chose that value.
  2. Write what the robot should do in each of these three cases:
  1. 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:

Lesson summary

Check questions

  1. How does an ultrasonic sensor measure distance?
  2. What does "threshold" mean, and why do we set it for the robot?
  3. If the measured distance is greater than the threshold, what should the robot do?
  4. Why is filtering needed? Give an example.
  5. Why should we power the motors from a separate battery and motor driver instead of directly from an Arduino pin?

Answers

  1. 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.
  2. 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.
  3. It means the way is clear, so the robot keeps moving forward.
  4. 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.
  5. 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.

Start QuizBack to Robotic Systems
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.