Build an Obstacle-Avoiding Robot Car with an Arduino
Build a robot car that drives by itself and turns away from walls, with an Arduino Uno, an L298N, two TT gear motors and an HC-SR04 at the front. When something is closer than 25 cm, it backs up, spins right and drives on.
It builds on the DC motor guide, which covers the L298N, its jumpers and PWM, and the HC-SR04 guide, which covers how the sensor measures distance. Here both of the L298N's channels are in use: A for the left motor, B for the right.
Try it first, no parts needed
Here is the car in a room, and under it its whole circuit, running in your browser. Press Run simulation: the sketch drives the car across the room with its two motors. When the HC-SR04 sees something closer than 25 cm, the car backs up, spins right and drives on. Every move comes from the sketch.
Arduino Uno serial monitor115200 baud
What the code does
Ten times a second, more or less, the sketch measures the distance ahead. Clear, both motors drive forward; closer than 25 cm, the car backs up and turns before measuring again.
// An obstacle-avoiding robot car: two motors on an L298N and an HC-SR04 at the front.
// It drives forward until something is closer than 25 cm, then backs up and turns.
const int ENA = 9, IN1 = 8, IN2 = 7; // left motor
const int ENB = 3, IN3 = 6, IN4 = 5; // right motor
const int TRIG_PIN = A1; // analog pins work as digital pins too
const int ECHO_PIN = A0;
const int SPEED = 140; // of 255: about 3.5 V for each motor on a 9 V supply
const int STOP_CM = 25; // closer than this, it turns away
// One motor: positive speed forward, negative backward, 0 coasts.
void setMotor(int en, int inA, int inB, int speed) {
digitalWrite(inA, speed > 0 ? HIGH : LOW);
digitalWrite(inB, speed < 0 ? HIGH : LOW);
analogWrite(en, abs(speed));
}
void drive(int left, int right) {
setMotor(ENA, IN1, IN2, left);
setMotor(ENB, IN3, IN4, right);
}
long distanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long echo = pulseIn(ECHO_PIN, HIGH, 30000); // 0 if no echo came back in 30 ms
if (echo == 0) {
return 400; // assumed clear; a loose ECHO wire looks the same
}
return echo / 58;
}
void setup() {
Serial.begin(115200);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
long cm = distanceCm();
if (cm < STOP_CM) {
Serial.print(cm);
Serial.println(" cm: obstacle, backing up and turning");
drive(-SPEED, -SPEED); // back up
delay(500);
drive(SPEED, -SPEED); // spin right
delay(400);
} else {
Serial.print(cm);
Serial.println(" cm: clear, forward");
drive(SPEED, SPEED);
}
delay(100);
}const int TRIG_PIN = A1; // analog pins work as digital pins tooThe two motors take six of the Uno's pins. Only ENA and ENB need PWM, on pins 9 and 3; IN3 and IN4 happen to be on 6 and 5, which can do PWM too but here are plain outputs. The sensor goes on A1 and A0, which work as ordinary digital pins.
const int SPEED = 140; // of 255: about 3.5 V for each motor on a 9 V supplyThe driving speed. With the L298's typical drop, a 9 V battery gives the motors pulses of about 6.45 V, so 140 of 255 averages about 3.5 V, inside a TT motor's 3 to 6 V, and slow enough to watch.
void setMotor(int en, int inA, int inB, int speed) { digitalWrite(inA, speed > 0 ? HIGH : LOW); digitalWrite(inB, speed < 0 ? HIGH : LOW); analogWrite(en, abs(speed)); }One motor: a positive speed sets its inputs for forward, a negative one for backward, and 0 sets both LOW with the enable at 0, so it coasts.
drivecalls it for both motors.long echo = pulseIn(ECHO_PIN, HIGH, 30000); // 0 if no echo came back in 30 msMeasures the echo, as in the HC-SR04 guide; dividing by 58 gives centimetres. With no echo within 30 ms the sketch assumes nothing is in range and returns 400, so the car drives on. A loose ECHO wire, or something too small or slanted to send sound back, looks the same: check the distances it prints before you let it go.
drive(-SPEED, -SPEED); // back upCloser than 25 cm: both motors backward for half a second.
drive(SPEED, -SPEED); // spin rightThen the left motor forward and the right backward: the car turns on the spot, to the right. The motors keep turning through the 0.4 s here and the 0.1 s at the end of
loop(), until the next reading sets them again: about half a second in all.drive(SPEED, SPEED);Clear ahead: both motors forward, until the next reading 0.1 s later.
How the car decides
The car steers like a tank: it has no steering wheel, only the speed and direction of each side. Both forward drives it straight; one forward and one backward turns it on the spot.
The L298N works as in the DC motor guide, with both of its H-bridges in use. The figure under this follows both in the running circuit.
The left motor
- IN1, pin 8
- HIGH
- IN2, pin 7
- LOW
- ENA, pin 9
- PWM 55%
- Bridge
- Forward
- Motor
- +3.5 V
The left motor: forward, switched on 55% of the time, averaging +3.5 V.
The right motor
- IN3, pin 6
- HIGH
- IN4, pin 5
- LOW
- ENB, pin 3
- PWM 55%
- Bridge
- Forward
- Motor
- +3.5 V
The right motor: forward, switched on 55% of the time, averaging +3.5 V.
Build it
Now with real parts. Put the chassis together, wire it, get the code, then test it with the wheels off the table before you let it go.
You'll need
- An Arduino Uno and its USB cable
- A two-wheel robot car chassis with two TT gear motors (Adafruit 3777: 3 to 6 V) and a caster wheel
- An L298N motor driver module, with both jumpers taken off ENA and ENB
- An HC-SR04 ultrasonic sensor
- For the motors, a 9 V battery or six AA cells in a holder; to drive untethered, a second 9 V battery for the Uno
- Jumper wires, and a small screwdriver for the terminals
- Software to upload the sketch: Cirkit Designer, free in your browser, or the Arduino IDE
Wire it
Take the jumpers off ENA and ENB first. Then seven wires from the L298N to the Uno, the battery to the power terminal, a motor on each side, and the sensor at the front. Connect the battery last.
Tap a connection to see it on the circuit.
From Connect to Show L298N GND Uno GND Show L298N ENA Uno pin 9 Show L298N IN1 Uno pin 8 Show L298N IN2 Uno pin 7 Show L298N IN3 Uno pin 6 Show L298N IN4 Uno pin 5 Show L298N ENB Uno pin 3 Show Battery + L298N 12V Show Battery − L298N GND Show L298N OUT1 Left motor Show L298N OUT2 Left motor's other lead Show L298N OUT3 Right motor Show L298N OUT4 Right motor's other lead Show HC-SR04 VCC Uno 5V Show HC-SR04 TRIG Uno A1 Show HC-SR04 ECHO Uno A0 Show HC-SR04 GND Uno GND Show On most chassis the motors face opposite ways. So the same wiring can turn one wheel forward and the other backward. If the car spins when it should drive straight, swap the leads of the motor that runs backward, as in troubleshooting.
Get the code
I'm using:Steps 2 and 3 follow the tool you pick.
The project opens with the sketch already in it. It needs no library.
The sketch needs no library. Copy it into a new sketch:
How it works line by line is in what the code does, above.
Upload and check it
Plug in your Uno. In Cirkit, open the Build tab, then Upload firmware: click Select Port and pick your Uno, then Upload to Device. Then open Upload output and serial monitor and click Start Serial Monitor. Stand the car on something so its wheels are off the table, then connect the battery.
Show me where to click in Cirkit
Select a device port
Select the device port for uploading code and serial communications
COM3 (Arduino Uno)- Open Build
- Choose Upload firmware
- Click Select Port
- Pick COM3 (Arduino Uno)
- Click Upload to Device
- Open Upload output and serial monitor
- Click Start Serial Monitor
In the Arduino IDE, choose Arduino Uno and its port from the board menu, press Upload, then open the Serial Monitor and set it to 115200 baud. Stand the car on something so its wheels are off the table, then connect the battery.
Show me where to click in the Arduino IDE
ObstacleCar.ino// An obstacle-avoiding robot car: two motors on an L298N and an HC-SR04 at the front. // It drives forward until something is closer than 25 cm, then backs up and turns. const int ENA = 9, IN1 = 8, IN2 = 7; // left motor const int ENB = 3, IN3 = 6, IN4 = 5; // right motor const int TRIG_PIN = A1; // analog pins work as digital pins too const int ECHO_PIN = A0;
OutputSerial Monitor115200 baudCompiling sketch...
Sketch uses 3162 bytes (9%) of program storage space. Maximum is 32256 bytes.
Global variables use 246 bytes (12%) of dynamic memory, leaving 1802 bytes for local variables. Maximum is 2048 bytes.
Uploading...
99 cm: clear, forward
61 cm: clear, forward
33 cm: clear, forward
21 cm: obstacle, backing up and turning
120 cm: clear, forward
Done uploading.
- Click the board menu
- Pick Arduino Uno on COM3
- Click Upload
- Wait for Done uploading
- Click Serial Monitor
- Check it is set to 115200 baud
It works when:
- With nothing in front of it, the Serial Monitor prints the distance and
clear, forward, and both wheels turn forward. - With your hand closer than 25 cm, it prints
obstacle, backing up and turning: both wheels run backward, then the left one forward and the right one backward. - On the floor, it drives up to a wall, backs off and turns away.
Device Serial99 cm: clear, forward61 cm: clear, forward33 cm: clear, forward21 cm: obstacle, backing up and turning120 cm: clear, forwardOutputSerial Monitor99 cm: clear, forward61 cm: clear, forward33 cm: clear, forward21 cm: obstacle, backing up and turning120 cm: clear, forwardLet it drive by itself
Unplug the USB cable and give the Uno its own 9 V battery on its DC jack, which Arduino's datasheet rates for 7 to 12 V. Keep the motors on their own battery, as in the circuit.
Not working? See troubleshooting.

Troubleshooting
Find your symptom; the checks under it run from the most common cause down.
It spins or circles when it should drive straight
- One motor runs backward. With the wheels off the table, see which one turns the wrong way and swap its leads in the L298N's terminal.
- One motor is slower. TT motors vary from one to the next, as Adafruit notes. Lower the faster side's speed a little in
drive.
One motor never turns
- Its enable is wired, with the jumper off. ENA goes to pin 9 for the left motor, ENB to pin 3 for the right.
- Its inputs are on the right pins. IN1 and IN2 go to 8 and 7, IN3 and IN4 to 6 and 5.
- Its leads are tight. The left motor's in OUT1 and OUT2, the right's in OUT3 and OUT4.
It always backs up and turns, even in the open
- The distance it prints is right. If it's tiny or 0, check the sensor's TRIG on A1, ECHO on A0, VCC on 5V and GND, as in HC-SR04 troubleshooting.
- The sensor sees the floor or the chassis. Its beam spreads about 15°: mount it at the front, level and a few centimetres up.
It hits walls, or misses chair legs
- It's too fast to stop in time. Lower
SPEED, or raiseSTOP_CM. - The thing is small, thin or slanted. The HC-SR04's datasheet asks for a target of at least 0.5 m², as smooth as possible; it may miss a chair leg.
Make it yours
- Change the speed: faster covers more ground but stops in more distance; slower is easier to watch. Below about 120 a TT motor on a 9 V battery gets less than its 3 V.
In place of the SPEED line const int SPEED = 180; // faster: less time to stop - Turn left instead: swap the two speeds in the turn.
In place of the spin right line drive(-SPEED, SPEED); // spin left
FAQ
Why is the sensor on A1 and A0?
The L298N takes six pins, and its two enables need PWM pins, 9 and 3 here. Arduino's analog pins can be used just like digital pins, which leaves the sensor two pins free of the motors.
Can I power the Uno from the L298N's 5V terminal?
Handson Technology shows it, wired to the Uno's 5V pin with the 5V-EN jumper on. That feeds the Uno past its own regulator, so it gets whatever the L298N's gives; a separate battery on the DC jack keeps the Uno on its own.
Can I build it on an ESP32?
Yes: the L298N's inputs take 3.3 V, as in the ESP32 guide. The HC-SR04's ECHO gives 5 V, so it needs a divider to the ESP32, as in the HC-SR04's ESP32 guide.
Simulating the robot car in Cirkit Designer
The L298N and both motors are simulated as in the DC motor guide, and the HC-SR04 as in the HC-SR04 guide. The room is drawn by this page: each motor counts its shaft's turns from the voltage across it, and the page rolls each wheel 63 mm across, the size of Adafruit's TT motor wheel, that far, on a car 13 cm between its wheels, the drawing's own size. It then tells the HC-SR04 the distance to the nearest wall or box along seven lines across its 15° measuring angle, or that nothing is within 4 m. The sketch decides everything the car does. The page hears from the circuit about 20 times a second, so the car and what the HC-SR04 is told trail the sketch by about 50 ms, a couple of centimetres at its speed; while the tab is hidden, the circuit pauses.
The motors turn as if nothing slowed them, about 33 RPM for each volt, so the car drives and turns faster than a real one carrying its weight on a floor: each spin turns it much further. Both motors are the same, so it drives perfectly straight where a real car drifts; it stops dead against a wall; and every surface echoes, where a real HC-SR04 can miss something small, soft or slanted.
References
- ST L298 dual full-bridge driver datasheet
- Handson Technology: L298N dual H-bridge motor driver user guide (powering an Arduino from the module)
- HC-SR04 datasheet (ElecFreaks, hosted by SparkFun)
- Adafruit: DC gearbox (TT) motor, 200 RPM, 3 to 6 V (product 3777)
- Adafruit: wheel for TT DC gearbox motors, 63 × 29 mm (product 3766)
- Arduino Uno Rev3 datasheet (DC jack 7 to 12 V)
- Arduino: analogWrite() (PWM pins)
- Arduino: analog input pins (usable as digital pins)
- Arduino: pulseIn()

