Arduino Obstacle Avoiding & Bluetooth Robot Car with L298N, HC-SR04 and Servo

Build an Arduino obstacle avoiding robot car that also drives from your phone over HC-05 Bluetooth: L298N motor driver, HC-SR04 on an SG90 servo scanner, buzzer, wiring table, diagram and full code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUArduino Uno / Nano
  • Parts11 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This Arduino obstacle avoiding robot car is a two-in-one build. In AUTO mode it drives by itself, uses an HC-SR04 ultrasonic sensor mounted on an SG90 servo to spot walls, then looks left and right and turns towards the clearer path. In MANUAL mode you drive it from your Android phone over an HC-05 Bluetooth module, and it still refuses to drive forward into a wall.

It is a big, combination-level project that brings together motor control with the L298N driver, PWM speed control, ultrasonic distance measurement, servo scanning, Bluetooth serial commands and simple decision-making. Everything runs on a single Arduino Uno (ATmega328P).

Arduino obstacle avoiding robot car wiring with L298N, HC-SR04 on SG90 servo, HC-05 Bluetooth and buzzer

How the Robot Car Works

  • Motor driver: the Arduino cannot power motors directly, so the L298N dual H-bridge does the heavy lifting. IN1/IN2 and IN3/IN4 set the direction of each motor, while PWM on ENA (D5) and ENB (D6) sets the speed.
  • Seeing obstacles: the HC-SR04 sends a 40 kHz ultrasonic pulse and times the echo. Distance in cm is the echo time in microseconds divided by 58. The code takes three readings and uses the middle one to ignore false spikes.
  • AUTO mode: above 45 cm the car drives at full set speed, between 25 and 45 cm it slows down, and under 25 cm it stops, beeps, backs up a little and turns the servo to measure the left and right sides. It turns towards the side with more space, or turns around if both sides are blocked.
  • MANUAL mode: the HC-05 receives single-letter commands (F, B, L, R, S and more) from a free Bluetooth RC car app or any serial terminal app. Keys 0 to 9 set the speed.
  • Safety features: the car starts in MANUAL mode and stopped. In manual mode it stops if no command arrives for 1.5 seconds (for example when you walk out of range), and a forward command is ignored if an obstacle is closer than 25 cm.
  • Feedback: the buzzer beeps on obstacles and mode changes, and the robot sends the measured left and right distances back to your phone app.

Components Required

  • Arduino Uno R3 (ATmega328P) or Arduino Nano – 1
  • L298N dual H-bridge motor driver module – 1
  • BO gear motors (3–6 V) with wheels – 2
  • 2WD robot car chassis with caster wheel – 1
  • HC-SR04 ultrasonic distance sensor – 1
  • SG90 micro servo with sensor bracket – 1
  • HC-05 Bluetooth module – 1
  • Active buzzer (5 V) – 1
  • Resistors: 1 kΩ and 2 kΩ (voltage divider for HC-05 RXD) – 1 each
  • 2 × 18650 Li-ion cells (7.4 V) with holder and an on/off switch – 1 set
  • Jumper wires (male-female and male-male)

Wiring Table

Module pinArduino Uno pinNotes
L298N ENAD5 (PWM)Remove the ENA jumper cap first
L298N IN1 / IN2D7 / D8Left motor direction
L298N ENBD6 (PWM)Remove the ENB jumper cap first
L298N IN3 / IN4A0 / A1Right motor direction (analog pins used as digital)
L298N OUT1 / OUT2Left motorSwap the two wires if it runs backwards
L298N OUT3 / OUT4Right motorSwap the two wires if it runs backwards
L298N 12V terminalBattery + (7.4 V)Through the on/off switch
L298N GNDBattery – and Arduino GNDCommon ground is essential
L298N 5V outputServo red, HC-SR04 VCC, HC-05 VCCKeep the 5V-EN jumper on
Arduino VINBattery + (after switch)Powers the Arduino from the same pack
HC-SR04 TRIG / ECHOA2 / A3GND to common ground
SG90 signal (orange)D10Brown wire to GND
HC-05 TXDD2SoftwareSerial RX
HC-05 RXDD4 through 1 kΩ, with 2 kΩ to GNDDrops 5 V to about 3.3 V for the HC-05
Active buzzer +A4Buzzer – to GND

Connection Diagram

The illustration above shows the general layout of the robot. The pin-accurate drawing below matches the wiring table exactly, so follow this one when you connect the wires.

Arduino Obstacle Avoiding & Bluetooth Robot Car – Pin-Accurate Wiring Arduino Uno D5 (PWM) L298N ENA (remove ENA jumper) – left motor speed D7 L298N IN1 D8 L298N IN2 D6 (PWM) L298N ENB (remove ENB jumper) – right motor speed A0 L298N IN3 A1 L298N IN4 A2 HC-SR04 TRIG A3 HC-SR04 ECHO D10 SG90 servo signal (orange) D2 HC-05 TXD D4 1k ohm -> HC-05 RXD (2k ohm from RXD to GND) A4 Active buzzer + (buzzer – to GND) VIN Battery + (7.4 V) – same wire as L298N 12V terminal GND Battery -, L298N GND and every module GND (common) L298N 5V output -> servo red wire, HC-SR04 VCC and HC-05 VCC. L298N OUT1/OUT2 -> left motor, OUT3/OUT4 -> right motor. Keep the 5V-EN jumper on the L298N (battery under 12 V). Swap a motor’s two wires if it spins the wrong way.
Pin-accurate connection diagram for the Arduino obstacle avoiding and Bluetooth robot car.

Arduino Code

Open the Arduino IDE, select Arduino Uno as the board and upload the sketch below. It only uses the built-in Servo and SoftwareSerial libraries, so nothing extra needs to be installed. Disconnect the HC-05 TXD wire from D2 while uploading if the upload fails. The sketch compiles to about 6.4 KB.

/*
  Arduino Obstacle Avoiding & Bluetooth Robot Car
  Board : Arduino Uno / Nano (ATmega328P)
  Parts : L298N motor driver, 2 x BO gear motors, HC-SR04 ultrasonic sensor
          on an SG90 servo, HC-05 Bluetooth module, active buzzer

  Two modes:
    AUTO   - drives forward, stops when something is closer than STOP_CM,
             looks left and right with the servo and turns to the clearer side.
    MANUAL - you drive it from any Android "Bluetooth RC Car" / serial
             terminal app over the HC-05.

  Bluetooth commands (single characters, 9600 baud):
    F = forward   B = back   L = left   R = right   S = stop
    G = forward-left   I = forward-right  (used by most RC car apps)
    0..9 = speed (0 = slowest, 9 = full)   q = full speed
    A = switch to AUTO mode     M = switch to MANUAL mode
    V = horn (buzzer beep)
*/

#include <Servo.h>
#include <SoftwareSerial.h>

// ---------- Pin map (matches the wiring table) ----------
const uint8_t ENA = 5;    // L298N ENA (PWM) - left motor speed
const uint8_t IN1 = 7;    // L298N IN1       - left motor direction
const uint8_t IN2 = 8;    // L298N IN2
const uint8_t ENB = 6;    // L298N ENB (PWM) - right motor speed
const uint8_t IN3 = A0;   // L298N IN3       - right motor direction
const uint8_t IN4 = A1;   // L298N IN4
const uint8_t TRIG_PIN = A2;   // HC-SR04 TRIG
const uint8_t ECHO_PIN = A3;   // HC-SR04 ECHO
const uint8_t SERVO_PIN = 10;  // SG90 signal (orange wire)
const uint8_t BUZZER_PIN = A4; // active buzzer +
const uint8_t BT_RX = 2;       // Arduino receives here  <- HC-05 TXD
const uint8_t BT_TX = 4;       // Arduino sends here     -> divider -> HC-05 RXD

// ---------- Tuning ----------
const int STOP_CM = 25;        // obstacle distance that makes the robot stop
const int SLOW_CM = 45;        // start slowing down below this distance
const int SERVO_CENTER = 90;   // adjust if the sensor does not face straight ahead
const int SERVO_LEFT = 165;
const int SERVO_RIGHT = 15;
const int TURN_MS = 380;       // time for roughly a 90 degree turn (tune on your floor)

Servo scanner;
SoftwareSerial bt(BT_RX, BT_TX);

enum Mode { MANUAL, AUTO };
Mode mode = MANUAL;            // start safely in MANUAL (stopped)
int speedPwm = 200;            // 0..255 motor speed
unsigned long lastCmdMs = 0;   // for the manual-mode safety timeout

// ---------- Motor helpers ----------
// dirL / dirR: 1 = forward, -1 = backward, 0 = stop
void drive(int dirL, int dirR, int pwm) {
  digitalWrite(IN1, dirL > 0);
  digitalWrite(IN2, dirL < 0);
  digitalWrite(IN3, dirR > 0);
  digitalWrite(IN4, dirR < 0);
  analogWrite(ENA, dirL == 0 ? 0 : pwm);
  analogWrite(ENB, dirR == 0 ? 0 : pwm);
}
void forward(int pwm)  { drive(1, 1, pwm); }
void backward(int pwm) { drive(-1, -1, pwm); }
void spinLeft(int pwm) { drive(-1, 1, pwm); }
void spinRight(int pwm){ drive(1, -1, pwm); }
void stopMotors()      { drive(0, 0, 0); }

void beep(int ms) {
  digitalWrite(BUZZER_PIN, HIGH);
  delay(ms);
  digitalWrite(BUZZER_PIN, LOW);
}

// ---------- Ultrasonic ----------
// Returns distance in cm, or 400 when nothing echoes back (open space).
int readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL);  // 25 ms timeout ~ 4 m
  if (us == 0) return 400;
  return (int)(us / 58UL);
}

// Take three readings and return the middle one to ignore odd spikes.
int medianDistance() {
  int a = readDistanceCm(); delay(8);
  int b = readDistanceCm(); delay(8);
  int c = readDistanceCm();
  if ((a <= b && b <= c) || (c <= b && b <= a)) return b;
  if ((b <= a && a <= c) || (c <= a && a <= b)) return a;
  return c;
}

int lookAt(int angle) {
  scanner.write(angle);
  delay(350);                 // let the servo arrive and stop shaking
  return medianDistance();
}

// ---------- AUTO mode ----------
void autoStep() {
  int front = medianDistance();

  if (front > SLOW_CM) {
    forward(speedPwm);
  } else if (front > STOP_CM) {
    forward(max(120, speedPwm / 2));   // slow down near objects
  } else {
    // Obstacle: stop, back off a little, then look both ways
    stopMotors();
    beep(80);
    backward(170);
    delay(250);
    stopMotors();

    int left = lookAt(SERVO_LEFT);
    int right = lookAt(SERVO_RIGHT);
    scanner.write(SERVO_CENTER);
    delay(200);

    bt.print(F("Obstacle! L=")); bt.print(left);
    bt.print(F("cm R=")); bt.print(right); bt.println(F("cm"));

    if (left < STOP_CM && right < STOP_CM) {
      // Dead end: turn around
      spinRight(200);
      delay(TURN_MS * 2);
    } else if (left > right) {
      spinLeft(200);
      delay(TURN_MS);
    } else {
      spinRight(200);
      delay(TURN_MS);
    }
    stopMotors();
    delay(100);
  }
}

// ---------- Bluetooth commands ----------
void handleCommand(char c) {
  lastCmdMs = millis();
  if (c >= '0' && c <= '9') {             // speed 0..9 -> PWM 110..255
    speedPwm = map(c - '0', 0, 9, 110, 255);
    return;
  }
  switch (c) {
    case 'q': speedPwm = 255; break;
    case 'A':
      mode = AUTO;
      scanner.write(SERVO_CENTER);
      beep(60); delay(80); beep(60);
      bt.println(F("AUTO mode"));
      break;
    case 'M':
      mode = MANUAL;
      stopMotors();
      beep(150);
      bt.println(F("MANUAL mode"));
      break;
    case 'V': beep(200); break;
  }
  if (mode != MANUAL) return;              // drive keys only work in MANUAL

  switch (c) {
    case 'F':
      // Even in manual mode, refuse to drive into a wall
      if (readDistanceCm() <= STOP_CM) { stopMotors(); beep(40); }
      else forward(speedPwm);
      break;
    case 'B': backward(speedPwm); break;
    case 'L': spinLeft(speedPwm); break;
    case 'R': spinRight(speedPwm); break;
    case 'G': drive(0, 1, speedPwm); break;   // forward-left (pivot)
    case 'I': drive(1, 0, speedPwm); break;   // forward-right (pivot)
    case 'S': stopMotors(); break;
  }
}

void setup() {
  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);
  pinMode(BUZZER_PIN, OUTPUT);
  stopMotors();

  scanner.attach(SERVO_PIN);
  scanner.write(SERVO_CENTER);

  Serial.begin(9600);   // USB debug
  bt.begin(9600);       // HC-05 default baud rate
  bt.println(F("Robot ready. Send A for AUTO, M for MANUAL."));
  beep(100);
}

void loop() {
  while (bt.available()) {
    char c = bt.read();
    if (c != '\r' && c != '\n') handleCommand(c);
  }

  if (mode == AUTO) {
    autoStep();
  } else {
    // Safety: stop if the phone stops sending for 1.5 s (out of range)
    if (millis() - lastCmdMs > 1500) stopMotors();
  }
}

Bluetooth Commands

CommandAction
ASwitch to AUTO (obstacle avoiding) mode
MSwitch to MANUAL mode and stop
F / BForward / backward
L / RSpin left / spin right
G / IForward-left / forward-right pivot
SStop
0 to 9, qSet speed (0 slowest, 9 or q full speed)
VHorn (buzzer beep)

Setup and Testing

  • Lift the car so the wheels are off the table, switch on the battery and pair your phone with the HC-05 (default PIN 1234 or 0000).
  • Open a Bluetooth RC car or serial terminal app, connect to the HC-05 and press F. Both wheels should turn forward. If one turns backwards, swap that motor’s two wires on the L298N.
  • Hold your hand 15 cm in front of the sensor and press F again. The car should beep and refuse to move forward.
  • Put the car on the floor and send A. It should drive, slow down near objects, stop, scan left and right, and turn away.
  • Tune TURN_MS so one turn is about 90 degrees on your floor, and change SERVO_CENTER if the sensor does not face straight ahead.

Power Tips

Two 18650 cells (7.4 V) are a good choice. The L298N drops about 2 V across its transistors, so the motors get roughly 5 to 6 V, which suits BO motors. Do not power the motors from the Arduino 5V pin or a 9 V PP3 battery; the 9 V battery cannot give enough current and the robot will keep resetting. Always join all grounds together.

Troubleshooting

ProblemFix
Car resets or the servo twitches when motors startUse fresh 18650 cells, add a 470 uF capacitor across the 5V and GND rails, and keep motor wires away from signal wires.
Motors hum but do not turnSpeed is too low. Send 9 or q, or raise the minimum value in the map() line.
Always sees an obstacleCheck TRIG and ECHO are not swapped and that the sensor is not pointing at the floor or chassis.
Phone connects but car does not respondHC-05 TXD must go to D2, and the baud rate must be 9600. Check the 1 kΩ / 2 kΩ divider on RXD.
Car stops by itself in manual modeUse an app that repeats the command while the button is held; the 1.5 s safety timeout stops the car otherwise.
Turns too much or too littleAdjust TURN_MS in the sketch.

Ideas to Extend

  • Add two IR line sensors and a third mode for line following.
  • Add IR sensors on the sides for better wall following in narrow spaces.
  • Replace the Uno and HC-05 with an ESP32 to drive the car from a web page over Wi-Fi.
  • Add an MPU6050 gyro so turns are exactly 90 degrees regardless of floor or battery level.

1 thought on “Arduino Obstacle Avoiding & Bluetooth Robot Car with L298N, HC-SR04 and Servo”

Leave a Comment