Guides · By the Faber team at DeadcowLabs, Inc. · Published 2026-11-17 · Parts and steps checked against the sources below

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

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

  1. Build the chassis. Mount both motors, wheels and the caster. Find a spot for the battery low and central.
  2. Mount the boards on the top plate. Keep the L298N's heat sink uncovered.
  3. Mount the sensor at the front, level and facing forward, with nothing in front of the two "eyes."
  4. Wire the motors to OUT1-OUT4, then the driver pins to the Uno, then the sensor, following the table.
  5. Wire power last, with the battery switch off. Double-check polarity: red to +, black to GND.
  6. 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.
  7. Upload the robot sketch below with the robot on a box, wheels in the air.
  8. 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:

  1. Measure the distance.
  2. If something is closer than a threshold (we use 25 cm), stop, reverse briefly, then turn left or right at random.
  3. 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

Faber's repo includes exactly this rover as an example: Uno, L298N, two DC motors, HC-SR04, 2WD chassis and a 2S battery. In Faber (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

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

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 →
Faber 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

Rules change. If something here is out of date, email hello@fabwright.dev and we'll fix it. See our editorial policy.

Faber · Latin for maker