artificial-intelligence
How to Implement Obstacle Avoidance in Mobile Robots Using Ultrasonic Sensors
Table of Contents
Understanding Ultrasonic Sensors
Ultrasonic sensors are a cornerstone of affordable robotics perception. They operate on the principle of echolocation: a transducer emits a burst of high-frequency sound waves (typically 40 kHz) that travel through the air, reflect off an object, and return as an echo. The sensor measures the time elapsed between emission and reception, often referred to as the "time of flight." Using the speed of sound in air (approximately 343 m/s at 20°C), the distance to the obstacle is calculated by the formula:
Distance = (Time of Flight × Speed of Sound) / 2
The division by two accounts for the round trip of the sound wave. Common modules such as the HC‑SR04, HY‑SRF05, and the PING))) sensor all follow this principle. Their typical range is from 2 cm to 4 meters, with an accuracy of about ±3 mm under ideal conditions. Because they rely on sound rather than light, ultrasonic sensors perform well in low-light, dusty, or foggy environments where optical sensors might fail. However, soft or sound-absorbing materials (e.g., fabric, foam) can reduce reliability, and multiple sensors operating in the same frequency band may cause crosstalk.
To ensure reliable obstacle avoidance, a thorough understanding of the sensor’s beam pattern is essential. Most ultrasonic transducers emit a cone-shaped beam with a half‑angle of about 15–30 degrees. Objects within that cone will produce an echo; objects outside it may be missed. Mounting the sensor at the correct height and tilt on your robot helps maximize coverage of typical obstacles like walls, furniture, or humans.
Hardware Components for Obstacle Avoidance
Building a mobile robot that can navigate around obstacles requires more than just a sensor. Below is a comprehensive list of hardware, including considerations for each choice.
Mobile Robot Platform
Select a chassis that suits your environment. Two-wheel differential drive (with a caster) is common for indoor robots because of its simplicity and tight turning radius. Four‑wheel or tracked platforms are better for rough terrain but require more complex motor control. Ensure the platform can carry the weight of the microcontroller, batteries, and sensors.
Ultrasonic Sensor Module
The HC‑SR04 is the most popular choice for hobbyists and prototyping. It has four pins: VCC (5V), GND, Trigger, and Echo. The HY‑SRF05 is a pin‑compatible upgrade with a single pin for both trigger and echo (selectable via a jumper). For projects requiring higher accuracy or multiple sensors, consider the MaxBotix MB1240 or the TFmini LiDAR as an alternative, though this article focuses on ultrasonic implementation.
Microcontroller
Arduino Uno or Nano is sufficient for basic obstacle avoidance with one or two ultrasonic sensors. For advanced algorithms (e.g., SLAM, sensor fusion) or if using a Raspberry Pi, you’ll need to manage GPIO timing accurately. The Raspberry Pi’s non‑real‑time OS can introduce jitter; a common workaround is to use a dedicated timing chip (e.g., an ATtiny) as a co‑processor.
Motor Driver and Power Supply
A dual H‑bridge motor driver such as the L298N or TB6612FNG is required to control the robot’s DC motors. The motors and the microcontroller often need separate voltage sources—use a battery pack that provides 6–12V for the motors and a 5V regulator for the logic. Fuses and capacitors are important to protect against voltage spikes when the motors start or stop.
Wiring and Mounting
Use female‑to‑female jumper wires for breadboard prototyping. For a robust final build, solder the connections or use screw terminals. Mount the ultrasonic sensor at the front of the robot, ideally on a servo so it can be swept left and right to widen the field of view. A pan‑tilt mechanism can further improve coverage, but adds weight and complexity.
Basic Obstacle Avoidance Algorithm
The core logic for obstacle avoidance is a reactive control loop. The robot continuously polls the distance sensor and makes decisions based on a predefined threshold. While more advanced planners (e.g., potential fields) exist, the simple “stop‑turn‑go” method is reliable and easy to implement.
Distance Measurement Routine
To measure distance with an HC‑SR04, the microcontroller sends a 10‑microsecond pulse to the Trigger pin, then listens on the Echo pin. The Echo pin goes HIGH for a duration proportional to the time of flight. On Arduino, use pulseIn() to measure that duration. Convert to centimetres:
distance_cm = (duration / 2) / 29.1
The division by 29.1 is derived from the speed of sound in microseconds per centimetre. After each measurement, insert a short delay (e.g., 50 ms) to allow any reverberations to dissipate and prevent echo interference.
Reactive Control Logic
The following pseudocode represents the minimal viable algorithm:
while robot is active:
distance = measure_distance_from_sensor()
if distance < THRESHOLD:
stop_motors()
turn_random_direction() // e.g., turn left 90 degrees
else:
move_forward()
delay(100) // measurement period
Threshold selection: Set the threshold to a distance slightly greater than the robot’s stopping distance. For typical indoor robots moving at 0.5 m/s, a threshold of 30–50 cm works well. Adjust based on robot speed and braking capability.
Adding Randomness to Turns
If your robot always turns the same direction (e.g., left) when encountering an obstacle, it can get stuck in loops (e.g., cornering forever). Introduce a random element: pick a turn direction at random when an obstacle is detected, or vary the turn angle between 45° and 135°. This simple heuristic, known as “random walk,” works surprisingly well in cluttered environments.
Improving Reliability with Filtering and Calibration
Raw ultrasonic readings can be noisy due to acoustic reflections, sensor crosstalk, or electrical interference. Applying filters stabilises the distance estimates and reduces false positives.
Moving Average Filter
Keep a small buffer (e.g., 5 samples) of recent distance values. When a new measurement arrives, replace the oldest value and compute the average. This smooths out spurious readings caused by sudden echoes from angled surfaces. The trade‑off is a slightly delayed response—acceptable for low‑speed robots.
Median Filter
For environments with impulse noise (e.g., occasional erroneous reads due to crosstalk), a median filter is better. Take the middle value from the sorted buffer. This eliminates outliers more effectively than the average.
Sensor Calibration Procedure
- Place the robot in an open area with a flat wall at a known distance (e.g., 100 cm).
- Run the sensor reading code and log at least 50 measurements.
- Compute the average deviation from the true distance. Use that offset as a calibration constant in your code: calibrated_distance = measured_distance + offset.
- If the sensor is mounted at an angle, you may need to apply a cosine correction based on the beam angle relative to the obstacle surface.
Advanced Techniques for Complex Environments
Once the basic obstacle avoidance works, you can enhance your robot’s navigation with more sophisticated methods.
Multiple Ultrasonic Sensors
Most robots benefit from at least three sensors: front, left, and right. With three sensors, the robot can decide whether to turn left or right when the front detects an obstacle—avoiding the random guess. More sensors (e.g., a ring of six or eight) allow for smoother path planning. When using multiple sensors, ensure their trigger pulses are spaced sufficiently apart (e.g., > 50 ms) to prevent one sensor’s echo from being picked up by another. Alternatively, stagger the sensor readings so that only one is active at a time.
Sensor Fusion with Infrared or LiDAR
Ultrasonic sensors excel at detecting transparent objects (e.g., glass walls) that infrared or laser sensors often miss. Conversely, LiDAR provides high‑resolution 2D scans ideal for mapping. Fusing ultrasonic data with a low‑cost infrared range finder (like the Sharp GP2Y0A21) can fill gaps in detection—especially for close ranges where ultrasonic sensors have a blind spot (the first 2 cm). Data fusion can be as simple as “take the minimum of the two sensors” or as complex as a Kalman filter for state estimation.
Implementing a Finite State Machine (FSM)
Replace the simple reactive loop with an FSM to handle more behaviours: “FORWARD”, “OBSTACLE_LEFT”, “OBSTACLE_RIGHT”, “TURNING”, “BACKING_UP”. Each state has a clear entry, action, and exit condition. This structure makes your code easier to debug and extend, e.g., adding a “SEARCH_FOR_PATH” state when the robot is surrounded.
Common Pitfalls and How to Avoid Them
Even with a well‑designed circuit and code, several practical issues can sabotage your obstacle avoidance system.
- Inaccurate timing due to microcontroller delays. Avoid using
delay()inside the measurement loop; use millis() or timers to keep the sensor polling independent of motor control. - Surface absorption. Soft surfaces (curtains, clothing) return a weak echo. Reduce the detection threshold or combine with an infrared sensor.
- Acoustic crosstalk between multiple sensors. Ensure only one sensor fires at a time. If you need simultaneous measurements, use sensors with different frequencies (e.g., 40 kHz and 25 kHz) or use a synchronized trigger series.
- Battery voltage drop affecting sensor performance. Regulate the sensor supply voltage precisely (5V ±0.25V). Low voltage can cause false triggers or reduced range.
- Robot getting stuck in corners. Implement a “backup” behaviour: if the robot turns repeatedly without making progress (detect with odometry or a wall‑following state), it should reverse a short distance before turning again.
Real-World Applications and Further Reading
Ultrasonic obstacle avoidance is used in many commercial and research systems: automatic vacuum cleaners (e.g., early Roomba models), warehouse robots, agricultural drones for ground‑level obstacle detection, and even assistive mobility devices. The principles scale up to larger platforms like autonomous guided vehicles (AGVs) in factories.
For a deeper dive, check out the following resources:
- Arduino official ultrasonic sensor tutorial – covers wiring and code for the HC‑SR04.
- MaxBotix Ultrasonic Sensor Selection Guide – explains beam patterns and accuracy.
- Research paper on sensor fusion for mobile robots (ScienceDirect) – advanced techniques using Kalman filters.
- RobotShop community forum discussion – practical tips from robotics enthusiasts.
- Wikipedia: Obstacle avoidance in mobile robotics – overview of reactive and planning methods.
Conclusion
Implementing obstacle avoidance with ultrasonic sensors is an accessible yet powerful way to give a mobile robot basic autonomy. By understanding the sensor’s physics, selecting the right components, writing clean reactive code, and adding filtering or multiple sensors, you can create a robot that reliably navigates cluttered spaces. Start with the simple algorithm described here, then incrementally add refinements such as random turns, sensor fusion, or state machines. With careful calibration and testing, your robot will be able to explore its environment, avoid collisions, and serve as a foundation for more advanced projects like mapping or SLAM.