Build an Obstacle Avoiding Robot
This robot drives forward on its own, and when the ultrasonic sensor sees a wall it stops, looks left and right with a servo, and turns toward the clearer side. It is a classic science fair and university project.
What You Need:
- 1x Arduino Uno R3
- 1x HC-SR04 Ultrasonic Sensor
- 1x SG90 Servo Motor
- 1x L298N Motor Driver
- 2x N20 gear motors with wheels and mounts
- 2x 18650 Li-ion batteries with holder (7.4V)
- Jumper Wires
1. Wiring
L298N Motor Driver:
- IN1, IN2, IN3, IN4 → Pins 5, 6, 9, 10
- OUT1/OUT2 → left motor, OUT3/OUT4 → right motor
- 12V → battery +, GND → battery − and Arduino GND
- 5V → Arduino VIN (keep the 5V jumper on)
Sensor and servo:
- HC-SR04 TRIG → A1, ECHO → A2, VCC → 5V, GND → GND
- Servo signal (orange) → Pin 3, red → 5V, brown → GND. Mount the HC-SR04 on the servo horn.
2. The Code
#include <Servo.h>
Servo head;
void drive(int a, int b, int c, int d) {
digitalWrite(5, a); digitalWrite(6, b);
digitalWrite(9, c); digitalWrite(10, d);
}
void forward() { drive(1,0,1,0); }
void back() { drive(0,1,0,1); }
void left() { drive(0,1,1,0); }
void right() { drive(1,0,0,1); }
void stopCar() { drive(0,0,0,0); }
long distanceCm() {
digitalWrite(A1, LOW); delayMicroseconds(2);
digitalWrite(A1, HIGH); delayMicroseconds(10);
digitalWrite(A1, LOW);
long d = pulseIn(A2, HIGH, 30000) * 0.0343 / 2;
return d == 0 ? 300 : d;
}
void setup() {
for (int p : {5, 6, 9, 10, A1}) pinMode(p, OUTPUT);
pinMode(A2, INPUT);
head.attach(3); head.write(90);
}
void loop() {
if (distanceCm() > 25) { forward(); delay(50); return; }
stopCar(); back(); delay(300); stopCar();
head.write(160); delay(400); long l = distanceCm();
head.write(20); delay(400); long r = distanceCm();
head.write(90); delay(200);
if (l > r) left(); else right();
delay(400); stopCar();
}3. Tuning
Change 25 to stop closer or farther, and the turn delay(400) to make sharper or softer turns.
Need help? Stuck on wiring or code? Message us on WhatsApp at +880 1577-098376 and we will help you with your project.
