Obstacle Avoiding Robot using Ultrasonic Sensor
Project Overview
This project combines sensors and actuators to create an autonomous robot capable of avoiding obstacles. It builds directly on your knowledge of ultrasonic distance measurement.
If you have not yet completed the ultrasonic sensor project, it is highly recommended to do so first: Ultrasonic Distance Sensor Project. This project depends on understanding how distance is measured before using it for decision-making in robotics.
The robot continuously scans the environment, detects obstacles, and reacts by changing direction. This demonstrates a core robotics principle where machines can sense their surroundings and act accordingly without human control.
Components Required
- Arduino Uno
- HC-SR04 Ultrasonic Sensor
- L298N Motor Driver
- 2 DC Motors with wheels
- Robot chassis
- Battery pack
- Jumper wires
Wiring Guide
Follow these steps:
- Connect the ultrasonic sensor as described in the previous project (Trig → Pin 6, Echo → Pin 7).
- Connect motor driver input pins to Arduino (e.g., IN1 → Pin 8, IN2 → Pin 9, IN3 → Pin 10, IN4 → Pin 11).
- Connect the DC motors to the output terminals of the motor driver.
- Provide external power to the motor driver using a battery pack.
- Connect all grounds together (Arduino GND and battery GND).
The motor driver is essential because the Arduino cannot supply enough current to run motors directly.
Source Code
if (distance < 20) {
stopMotors();
turnRight();
} else {
moveForward();
}
Code Explanation
The robot constantly reads the distance from the ultrasonic sensor.
If an object is detected within 20 cm, the robot stops and changes direction to avoid a collision. If no obstacle is detected, it continues moving forward.
This behavior follows a simple but powerful robotics model:
- Sense: Measure distance using the ultrasonic sensor
- Decide: Compare distance with a threshold value
- Act: Move or turn based on the decision
This project is your first step into autonomous robotics, where systems operate independently based on sensor input.