DC motor guides · On this page

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.

The car in a roomPress Run: the sketch drives this car with its two motors, and its HC-SR04 sees what is in front of it. The circuit is under the room.

Press Run to start the car.

Ready
Open in Cirkit Designer

Arduino Uno serial monitor115200 baud

Output appears here when the simulation runs.

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.

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;

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);
}
  1. const int TRIG_PIN = A1;  // analog pins work as digital pins too

    The 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.

  2. const int SPEED = 140;     // of 255: about 3.5 V for each motor on a 9 V supply

    The 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.

  3. 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. drive calls it for both motors.

  4. long echo = pulseIn(ECHO_PIN, HIGH, 30000);  // 0 if no echo came back in 30 ms

    Measures 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.

  5. drive(-SPEED, -SPEED);  // back up

    Closer than 25 cm: both motors backward for half a second.

  6. drive(SPEED, -SPEED);   // spin right

    Then 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.

  7. 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 car's loop. Read the distance with the HC-SR04, in centimetres. Under 25 cm? No: drive both motors forward at 140. Yes: back up, both motors backward for 0.5 seconds, then spin right, the left motor forward and the right backward, for about half a second. Then it reads the distance again.

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 H-bridge, liveExample: forward at 140 of 255Run the circuit at the top, and this follows the L298N as the sketch drives it.

The left motor

IN1, pin 8
HIGH
IN2, pin 7
LOW
ENA, pin 9
PWM 55%
Battery +GNDMOUT1OUT2
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%
Battery +GNDMOUT3OUT4
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
  1. 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.

    FromConnect toShow
    L298N GNDUno GNDShow
    L298N ENAUno pin 9Show
    L298N IN1Uno pin 8Show
    L298N IN2Uno pin 7Show
    L298N IN3Uno pin 6Show
    L298N IN4Uno pin 5Show
    L298N ENBUno pin 3Show
    Battery +L298N 12VShow
    Battery −L298N GNDShow
    L298N OUT1Left motorShow
    L298N OUT2Left motor's other leadShow
    L298N OUT3Right motorShow
    L298N OUT4Right motor's other leadShow
    HC-SR04 VCCUno 5VShow
    HC-SR04 TRIGUno A1Show
    HC-SR04 ECHOUno A0Show
    HC-SR04 GNDUno GNDShow

    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.

  2. Get the code

    I'm using:

    Steps 2 and 3 follow the tool you pick.

    Open in Cirkit Designer

    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.

  3. 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
    Obstacle-avoiding robot carFileEditExportHelp
    DesignCodeSimulateBuild
    1Parts & purchasing2Assemble3Upload firmware
    Arduino UnoEdit Code

    Board

    Arduino Uno Change

    2

    Port

    Select PortCOM3 Connected

    3

    Upload

    Upload to DeviceUploading...Upload successful

    4

    Check that it works

    Your project should now run as designed.

    Upload output and serial monitor
    Compile / Upload Output
    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.
    Device SerialStop

    Read serial data from your device.

    Start Serial Monitor
    Listening on COM3 at 115200 baud
    99 cm: clear, forward
    61 cm: clear, forward
    33 cm: clear, forward
    21 cm: obstacle, backing up and turning
    120 cm: clear, forward
    Select port

    Select a device port

    Select the device port for uploading code and serial communications

    COM3 (Arduino Uno)
    1. Open Build
    2. Choose Upload firmware
    3. Click Select Port
    4. Pick COM3 (Arduino Uno)
    5. Click Upload to Device
    6. Open Upload output and serial monitor
    7. 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
    Select BoardArduino Uno

    Select other board and port

    Arduino UnoCOM3
    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 baud

    Compiling 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.

    1. Click the board menu
    2. Pick Arduino Uno on COM3
    3. Click Upload
    4. Wait for Done uploading
    5. Click Serial Monitor
    6. 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.

    Let 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.

    Next guideUsing an ESP32? The motor has its own guideThe L298N and a DC motor on an ESP32: why its 3.3 V pins drive the inputs directly, and reading a knob in millivolts.

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 raise STOP_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