Arduino Obstacle-Avoiding Robot: Step-by-Step Build and Code
To build an Arduino obstacle-avoiding robot, mount an Arduino Uno, an L298N motor driver, two TT motors and an HC-SR04 ultrasonic sensor on a 2WD chassis, power the motors from a separate 7.4 V battery, and share all grounds. The code measures distance about 20 times a second: if something is closer than about 25 cm it stops, reverses and turns; otherwise it drives forward. Expect an afternoon of building and some tuning of speed and stop distance.
What you're building
A small two-wheel car that drives forward, "sees" a wall with an ultrasonic sensor, stops, backs up, turns and carries on. If you're brand new, our how to build a robot at home overview explains each piece in plain words first.
Parts list
Prices checked Nov 2026 at Adafruit and SparkFun.
| Part | Job | Approx. price |
|---|---|---|
| Arduino Uno R3 (or compatible) | Runs the program | $18-28 |
| L298N motor driver | Lets the small Arduino control the bigger motors | $5-10 |
| 2WD chassis with 2 TT DC motors, wheels, caster | Body and drive | $20-25 |
| HC-SR04 ultrasonic sensor | Measures distance (about 2-400 cm) | $4-6 |
| 2S 7.4 V battery pack with switch (or 4 x AA holder) | Motor and board power | $3-17 |
| Jumper wires, double-sided tape, small screws | Connections and mounting | varies |
For a full cost breakdown, see how much it costs to build a robot.
Why these parts
- TT motors are rated 3-6 V. Adafruit measured about 150 mA spinning freely and up to 1.5 A when stalled. That stall current is why motors must never run from Arduino pins or the Arduino 5V pin.
- The L298N takes 5-46 V on its motor input and handles up to 2 A per channel, but it loses about 2 V inside. Last Minute Engineers recommends about 7 V for TT motors, which is why a 2S (7.4 V) pack fits well.
- The HC-SR04 runs on 5 V. You pulse its TRIG pin for 10 microseconds, it sends a 40 kHz ping, and the ECHO pin stays high for as long as the sound takes to come back. Adafruit suggests 10-250 cm for best results, and the beam is about 15 degrees wide.
Wiring table
This pin map follows Automatic Addison's tutorial. ENA and ENB must be on PWM pins (marked with ~ on the Uno) so you can set speed.
| From | To | Notes |
|---|---|---|
| L298N ENA | Uno pin 9 | Left motor speed (PWM). Remove the ENA jumper first. |
| L298N IN1 | Uno pin 5 | Left motor direction |
| L298N IN2 | Uno pin 6 | Left motor direction |
| L298N IN3 | Uno pin 7 | Right motor direction |
| L298N IN4 | Uno pin 8 | Right motor direction |
| L298N ENB | Uno pin 10 | Right motor speed (PWM). Remove the ENB jumper first. |
| L298N OUT1 / OUT2 | Left motor | Swap these two if the wheel spins backward |
| L298N OUT3 / OUT4 | Right motor | Same |
| HC-SR04 VCC | Uno 5V | Sensor only, not motors |
| HC-SR04 TRIG | Uno pin 11 | |
| HC-SR04 ECHO | Uno pin 12 | |
| HC-SR04 GND | Uno GND | |
| Battery + (via switch) | L298N motor power (+12V / VS) and Uno VIN | Uno accepts 7-12 V on VIN |
| Battery minus | L298N GND and Uno GND | All grounds must be shared |
Keep the L298N's 5V-regulator jumper in place for a 7.4 V battery. Last Minute Engineers says to remove it only above 12 V.
Build steps
- Build the chassis. Mount both motors, wheels and the caster. Find a spot for the battery low and central.
- Mount the boards on the top plate. Keep the L298N's heat sink uncovered.
- Mount the sensor at the front, level and facing forward, with nothing in front of the two "eyes."
- Wire the motors to OUT1-OUT4, then the driver pins to the Uno, then the sensor, following the table.
- Wire power last, with the battery switch off. Double-check polarity: red to +, black to GND.
- Test the sensor alone. Upload a sketch that prints the distance to the Serial Monitor (9600 baud) and move your hand in front of it.
- Upload the robot sketch below with the robot on a box, wheels in the air.
- Run it on the floor in an open space.
How the code works
The logic is a loop that runs about 20 times per second:
- Measure the distance.
- If something is closer than a threshold (we use 25 cm), stop, reverse briefly, then turn left or right at random.
- Otherwise, drive forward.
Here is a short sketch based on that logic. The distance math divides the echo time in microseconds by 58 to get centimeters (the sound travels there and back). If no echo returns, pulseIn() gives 0, so we treat that as "nothing in range" rather than "touching the wall."
const int ENA = 9, IN1 = 5, IN2 = 6, IN3 = 7, IN4 = 8, ENB = 10;
const int TRIG = 11, ECHO = 12;
const int SPEED = 150; // 0-255
const int STOP_CM = 25;
long readCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000); // timeout about 30 ms
if (us == 0) return 999; // no echo: treat as clear
return us / 58;
}
void drive(int left, int right) { // -255 to 255
digitalWrite(IN1, left > 0); digitalWrite(IN2, left < 0);
digitalWrite(IN3, right > 0); digitalWrite(IN4, right < 0);
analogWrite(ENA, abs(left)); analogWrite(ENB, abs(right));
}
void setup() {
int pins[] = {ENA, IN1, IN2, IN3, IN4, ENB, TRIG};
for (int p : pins) pinMode(p, OUTPUT);
pinMode(ECHO, INPUT);
randomSeed(analogRead(A0));
}
void loop() {
if (readCm() < STOP_CM) {
drive(0, 0); delay(200);
drive(-SPEED, -SPEED); delay(400);
if (random(2)) drive(-SPEED, SPEED); else drive(SPEED, -SPEED);
delay(350);
} else {
drive(SPEED, SPEED);
}
delay(50);
}
Automatic Addison's version also averages four readings to smooth out noise.
Try it in a simulator first
Fabwright's repo includes exactly this rover as an example: Uno, L298N, two DC motors, HC-SR04, 2WD chassis and a 2S battery. In Fabwright (free and open source) the real compiled sketch drives the rover in a virtual arena, and the example's scenario test runs 30 virtual seconds with 0 collisions. It's a simulator with a simple electrical model, so the real robot still needs tuning, but it catches a wrong pin early.
Testing and tuning
- Speed: start around 120-150. Too fast and it hits walls before reacting; too slow and TT motors hum without moving (humming at low PWM is normal, per Last Minute Engineers).
- Stop distance: raise
STOP_CMif it still bumps walls. Faster robots need more room. - Turn time: change the
delay(350)after turning. Longer means a bigger turn. - Driving crooked: motors are never identical. Lower the speed of the faster side by 5-15.
Troubleshooting
| Problem | Likely cause and fix |
|---|---|
| Nothing moves | Missing shared ground, battery switch off, or ENA/ENB jumpers still on while pins also connected. Check every GND. |
| One wheel spins backward | Swap that motor's two wires on the L298N. |
| Arduino resets when motors start | Battery too weak or low. Charge or replace it, keep motor and logic grounds joined. |
| Robot reverses for no reason | Noisy readings. Print distances to the Serial Monitor; average several readings. |
| Misses chair legs or soft objects | The narrow 15 degree beam misses thin or angled things; fabric absorbs sound. Add bump switches. |
| L298N very hot or motors cut out | It shuts down when overheated. Lower speed, give it air. |
Safety notes
- LiPo / lithium packs: charge only with a charger for that exact pack (a 2S pack needs a 2-cell balance charger), never puncture, crush or short it, and stop if it swells, smells or gets hot. Don't leave it charging unattended.
- Motors: switch power off before rewiring, keep fingers and hair away from wheels.
- Never power motors from the Arduino 5V pin. Always through the L298N from the battery.
- Power sources: batteries or USB only. Never wall mains.
Next steps
Put the sensor on a servo so it can look left and right before turning, add an OLED face like a desk robot pet, or try other easy robots to build for beginners.
Try the wiring and code before you buy parts →Fabwright builds and tests your gadget in a simulator, then designs a case you can 3D print.
FAQ
Which Arduino pins does the L298N need?
Four direction pins (IN1-IN4) on any digital pins and two speed pins (ENA, ENB) on PWM pins. On an Uno, PWM pins are 3, 5, 6, 9, 10 and 11.
What battery should I use?
A 2S 7.4 V pack suits TT motors because the L298N drops about 2 V. Four AA cells (6 V) also work, just slower. Never run the motors from the Arduino's 5V pin.
Why does my robot keep hitting walls?
It's going too fast for its stop distance, or the sensor misses angled or soft surfaces. Lower the speed, raise the stop distance and check readings in the Serial Monitor.
Can I use an Arduino Nano instead of an Uno?
Yes. The Nano uses the same ATmega328P chip, so the same code works; just match the pin numbers to the Nano's pins.
Do I need a library for the HC-SR04?
No. The built-in pulseIn() function is enough. Some tutorials use the NewPing library for extra features.
Sources
- Last Minute Engineers: L298N motor driver with Arduino
- Automatic Addison: obstacle avoiding robot with Arduino and L298N
- Adafruit: HC-SR04 ultrasonic sonar distance sensor
- SparkFun: Ultrasonic Distance Sensor 5V (HC-SR04)
- Adafruit: TT DC gearbox motor 3-6 VDC
- Adafruit: Mini Round Robot Chassis Kit 2WD with DC motors
- SparkFun: Arduino Uno R3
- Adafruit Learn: Li-Ion and LiPoly batteries, safety
Rules change. If something here is out of date, email hello@fabwright.dev and we'll fix it. See our editorial policy.