Hello friends, I hope you all are doing great. Today, I am going to share the Obstacle Avoiding Robot using ESP32 and HC-SR04 - Proteus Simulation, project 101 of our IoT Projects series. The obstacle avoiding robot is probably the most popular first robot project of all, and for a good reason: with one ultrasonic sensor, one servo and two motors it already behaves like something alive. Here is a complete one, with the circuit, the code and a Proteus simulation you can run before you build anything.

The robot drives forward on its own and keeps measuring the distance ahead with an HC-SR04 ultrasonic sensor. When something comes closer it slows down, and when the way is blocked it stops, backs up, turns its head to look right and left, and drives off towards the side with more room. If both sides are blocked, it turns around. The head is the HC-SR04 mounted on an SG90 servo, the brain is an ESP32, and an L298N drives the two TT gear motors. Because it is an ESP32, there is also a dashboard: start and stop the robot and watch its decisions from a laptop or a phone. In this tutorial, we will go through the circuit, how the ultrasonic sensor measures distance, how the servo turns the head, how the L298N drives the wheels, the robot's decision logic and the code. Then we put walls in front of the robot in the simulation and watch it find its way. At the end, you can download the project with the sketch and every library file.

NOTICE: Our team has put a lot of effort into this project: the circuit, the code and every part in the simulation are our own work, and you get them all free. Your feedback is the fuel that keeps us going, so please tell us what you think in the comments below. And if our free projects help you, you can buy us a coffee. So, let's get started with the obstacle avoiding robot using ESP32 and HC-SR04 in Proteus simulation:

Figure: The obstacle avoiding robot in a Proteus simulation.
Figure: The project working in the Proteus simulation (an animation of the main steps).

What Does This Obstacle Avoiding Robot Do?

  • Drives by itself: forward at 80 % with a ping every 60 ms.
  • Slows down: from 60 cm the speed falls with the distance, down to 40 % at 25 cm.
  • Stops in time: under 25 cm it stops and backs up 0.4 s.
  • Looks around: the servo turns the sensor right and left and measures both sides.
  • Chooses a way: it turns towards the side with more room, or turns around when both are blocked.
  • A dashboard: START, STOP, the distances, the motors and every turn.

In the simulation, the HC-SR04's pop-up places the obstacle, the SG90's pop-up shows where the head is pointing, and the L298N and the motors' pop-ups show each wheel's voltage and speed.

Components Used in the Proteus Simulation

All the parts come from our Proteus libraries, each with its own tutorial. The project zip at the end includes every LIB and DLL file.

The parts of the obstacle avoiding robot and their library posts
PartProteus deviceLibrary postConnection
ESP32 DevKit V1ESP32 DEVKIT V1ESP32 DevKit V1 Library for ProteusU1, ESP32_Obstacle_Robot.hex, Wi-Fi 192.168.1.101
HC-SR04 ultrasonic sensorHCSR04ADVTEPHC-SR04 Ultrasonic Sensor Library for ProteusU2: TRIG D5, ECHO D18, VCC 5 V
SG90 servo motorSG90SERVOTEPSG90 Servo Motor Library for ProteusSERVO1: SIG D13, V+ 5 V (the head)
L298N motor driverL298NDRIVERTEPL298N Motor Driver Library for ProteusU3: ENA D32, IN1 D33, IN2 D25, ENB D14, IN3 D26, IN4 D27
TT gear motors (x 2)TTGEARMOTORTEPTT Gear Motor Library for ProteusM1 left, M2 right
Laptop WiFi MonitorLAPTOP WIFI MONITORLaptop WiFi MonitorPC1
Mobile WiFi MonitorMOBILE WIFI MONITORMobile WiFi MonitorMOB1

Proteus Simulation of the Robot: the Circuit

Figure: The complete circuit of the obstacle avoiding robot on an A3 Proteus sheet.
The connections of the obstacle avoiding robot
SignalESP32Goes to
TRIG / ECHOD5 / D18the HC-SR04
SERVOD13the SG90's signal (the head)
ENA, IN1, IN2D32, D33, D25the L298N: the left motor
ENB, IN3, IN4D14, D26, D27the L298N: the right motor
VCC (5 V)VINthe HC-SR04 and the SG90
+7.4V-the L298N's motor supply (a 2S Li-ion pack)

The motors run from their own 7.4 V pack through the L298N, never from the ESP32. The L298N's enable jumpers are removed so that the ESP32's PWM on ENA and ENB sets each wheel's speed, while IN1 - IN4 set the directions.

How the Obstacle Avoiding Robot Works

Measuring Distance with Sound

The HC-SR04 sends a burst of 40 kHz ultrasound when its TRIG pin gets a 10 microsecond pulse, and holds its ECHO pin HIGH until the echo comes back. Sound travels about 343 m/s, so the echo time in microseconds divided by 58 is the distance in centimetres (there and back). If no echo returns within 30 ms, nothing is within about 5 m. The robot pings every 60 ms, often enough for a small robot and slow enough that one ping's echo cannot be mistaken for the next.

A Servo as a Head

Instead of three sensors, the robot has one sensor that turns. The SG90 servo takes a pulse every 20 ms: 544 microseconds is 0 degrees, 2400 microseconds is 180 degrees. The ESP32 makes that pulse with its LEDC PWM at 50 Hz, so no servo library is needed. 90 degrees looks straight ahead, 20 degrees to the right, 160 degrees to the left. A servo needs time to swing, so the robot waits 0.6 s before it measures a side.

Driving Two Wheels with the L298N

The L298N holds two H-bridges, one per motor. IN1 and IN2 choose the left wheel's direction (one HIGH = forward, the other HIGH = backward, both LOW = stop), and the PWM on ENA sets its speed; IN3, IN4 and ENB do the same for the right wheel. A robot with two driven wheels steers by speed: both forward drives straight, one forward and one backward spins it on the spot. The sketch ramps every speed change by 5 % every 20 ms, so the robot never jolts.

The Decision Logic

The robot is a small state machine: FORWARD, BACKING UP, LOOKING RIGHT, LOOKING LEFT and TURNING. In FORWARD it pings and sets its speed from the distance. Under 25 cm it backs up for 0.4 s, which also gives the servo room to look around. It measures the right side, then the left side, turns its head straight again and decides: the side with more room wins; if both are closer than 40 cm, it is in a dead end and turns around. After the turn it drives on, and the loop starts again.

How Fast Must the Robot React?

At full cruise the wheels turn at about 190 RPM, which for a 65 mm wheel is roughly 0.65 m/s. Between two pings, 60 ms apart, the robot rolls about 4 cm, and the echo itself takes another 1.5 ms at 25 cm, which hardly counts. So when the sensor first sees an object at 25 cm, the robot is at most about 4 cm further on when it reacts. That is why the stop distance is 25 cm and not 10: there must be room for the time between pings, for the motors to stop, and for the robot to back up and turn without touching the obstacle. The slowing band from 60 cm down to 25 cm helps too, because a robot at 40 % speed covers only about 2 cm between pings. A faster robot needs a bigger stop distance or more frequent pings, and pinging much faster than every 30 ms risks hearing the echo of the previous ping.

The same reasoning explains the 0.6 s the robot waits after turning its head. An SG90 swings about 60 degrees in 0.1 s without a load; from 20 to 160 degrees it needs well under half a second, and the rest of the time lets the horn settle before the ping, so the reading belongs to the direction the robot meant to look.

The Arduino Code Explained

The sketch is ESP32_Obstacle_Robot.ino, built for our ESP32 DevKit V1 with the WiFi and WebServer libraries. The limits:

const float STOP_CM = 25, SLOW_CM = 60, CLEAR_CM = 40;

One ping:

  const unsigned long us = pulseIn(ECHO, HIGH, 30000);            // 30 ms: about 5 m and back
  return us ? us / 58.0f : 400.0f;                                // (no echo: nothing within range)

The servo's pulse from an angle, on a 50 Hz, 16-bit LEDC channel:

  const uint32_t us = 544 + (uint32_t)deg * (2400 - 544) / 180;
  ledcAttach(SERVO, 50, 16);

One wheel on the L298N: the direction pins, then the PWM:

  digitalWrite(a, pct > 0); digitalWrite(b, pct < 0);

In FORWARD: an obstacle, or a speed from the distance:

      if (dist < STOP_CM) {
        const int s = SLOW_MIN + (int)((dist - STOP_CM) / (SLOW_CM - STOP_CM) * (CRUISE - SLOW_MIN));

After looking both ways, the decision:

        if (leftCm < CLEAR_CM && rightCm < CLEAR_CM) {
        } else if (leftCm > rightCm) {

Every speed change is a ramp:

    speedNow[k] += constrain(d, -5, 5);

The dashboard's links are Refresh, START and STOP; /data gives the mode, the distances, the motors and the turns as JSON.

How to Run the Proteus Simulation

  1. Download the project zip below and install the library files (the steps are under the download button).
  2. Open ESP32-Obstacle-Robot.pdsprj from the Proteus Simulation folder. Keep the HEX and the DLL files next to it.
  3. Press Play, open the Laptop WiFi Monitor (press Go) and press START.
  4. Click U2 for the sensor's pop-up and move the obstacle closer: the robot slows down, then stops and looks around.
  5. Set a distance while it looks right and another while it looks left: it turns towards the bigger one.

Simulation Results: the Robot in Proteus

We pressed Play, started the robot from the laptop and put walls in front of it with the HC-SR04 pop-up's presets: one far away, one closer, one right in front, and then a dead end. The pop-ups show every ping, the servo's horn and each wheel's voltage and speed. The times are the sketch's clock; the whole run took 28.1 simulated seconds.

Ready and Driving

The ESP32 joined TEP-WiFi and reported READY - ahead 199.0 cm at 2.26 s: the wall at 200 cm, an echo of 11648 microseconds. The servo held the head straight ahead at 90 degrees, a 1472 microsecond pulse. We pressed START at 10.44 s; both wheels ramped up to 80 %: 4.70 V and 0.15 A for each motor, 190 RPM, 0.65 m/s at the wheel.

Figure: Ready.
Figure: The HC-SR04: 200 cm.
Figure: The servo: straight ahead.
Figure: The dashboard.
Figure: START.
Figure: Driving forward.
Figure: The L298N: both wheels at 80 %.
Figure: The left wheel: 190 RPM.
Figure: Pinging while it drives.

Slowing Down

We moved the wall to 50 cm. The next ping read 50.2 cm (an echo of 2912 microseconds), inside the 25 - 60 cm band, and the speed fell with the distance to 68 %, 3.99 V on each motor.

Figure: Slowing down.
Figure: The HC-SR04: 50 cm.
Figure: The L298N: 68 %.

Blocked: Look Right, Look Left, Turn

Then the wall at 10 cm. At 14.78 s: OBSTACLE at 9.9 cm - stop, back up. The robot backed up for 0.4 s and turned its head right; while it backed up we placed the right-hand wall at 25 cm. At 15.78 s it reported right: 25.0 cm - LOOK LEFT, and the servo's pop-up shows the head already swinging to the left, 43 degrees on its way to 160. With the left side clear at 200 cm, it reported left: 199.6 cm - TURN LEFT at 16.40 s, spun left for 0.45 s and was driving forward again at 16.85 s.

Figure: Looking right.
Figure: The servo swinging to the left.
Figure: The right side: 25 cm.
Figure: The left side clear: TURN LEFT.
Figure: The left side: 200 cm.
Figure: The dashboard: turned left.

A Dead End

Next, a dead end: 10 cm ahead, then 20 cm on the right and 15 cm on the left. At 21.68 s: left: 15.0 cm - both blocked: TURN AROUND. The L298N's pop-up shows the spin: bridge A forward at 60 %, bridge B reversed at 60 %, 3.49 V each way, for 0.9 s.

Figure: A dead end: turning around.
Figure: The L298N: spinning on the spot.
Figure: The left side: 15 cm.

We moved the wall away a moment after that turn ended, so the very first ping still caught it at 13.6 cm. The robot did what it should: it backed up and looked again, found 199.6 cm on both sides and turned right (with equal room it picks the right), then drove on at 24.66 s.

STOP from the Phone

Finally we pressed STOP on the phone at 25.08 s: both bridges coasted to 0 V. The dashboard counted 3 obstacles: 1 turn left, 1 turn right and 1 turn around, in 14 s of driving.

Figure: The phone.
Figure: STOP from the phone.
Figure: Stopped.
Figure: The L298N: off.
Figure: The dashboard at the end.

The serial monitor shows every decision:

Figure: The serial log.

Download the Project Files

Click the button below to download Obstacle-Avoiding-Robot-ESP32-HC-SR04-Proteus-Simulation-v1.0.zip (about 4.1 MB, without the source code of the models):

Obstacle Avoiding Robot using ESP32 and HC-SR04 - Proteus Simulation V1.0
  • Proteus Simulation: ESP32-Obstacle-Robot.pdsprj, ESP32_Obstacle_Robot.hex and copies of the models.
  • Arduino Code: ESP32_Obstacle_Robot.ino, the sketch.
  • Proteus Library Files: the LIB files of every part.
  • Proteus Model Files: the DLL models.
  • README.txt: the installation steps, the properties, the test results and the links to every library post.

No Proteus yet? Read How to Download and Install Proteus 7 and 8. New to libraries? Follow How to Install a New Library in Proteus.

How to Install the Project Files

  1. Close Proteus and extract the whole zip file, for example to your Desktop.
  2. Copy the files from Proteus Library Files into the LIBRARY folder of Proteus.
  3. Copy the files from Proteus Model Files into the MODELS folder.
  4. Start Proteus and open the project from the Proteus Simulation folder.

Changing the Code

Open the sketch in the Arduino IDE with the TEP Boards for Proteus installed, select ESP32 Dev Module (TEP Proteus), and use Sketch > Export Compiled Binary. Put the new HEX next to the project. The distances, the speeds and the times are near the top.

Ideas to Extend the Project

  • Add two IR sensors at the front corners to catch thin obstacles the ultrasonic beam misses.
  • Add wheel encoders and turn by angle instead of by time.
  • Remember the last turns and avoid going back and forth in a corridor.
  • Add a manual mode: drive the robot from the dashboard and let it take over when something is in the way.
  • Map the room: log every look with the servo angle and draw it on the dashboard.
  • Add a buzzer that beeps faster as an obstacle comes closer.

From Simulation to Real Hardware

  • The ECHO pin: the HC-SR04 runs on 5 V and so does its ECHO; put a 1 k / 2 k divider before the ESP32 pin.
  • Power: the motors from their own pack, the servo from a 5 V regulator, a common ground for everything.
  • The turn time: a real 90 degree turn depends on the wheels, the battery and the floor; tune TURN_MS on your robot.
  • Soft obstacles: cloth and sound-absorbing foam can return no echo; an IR sensor helps there.
  • Mounting: mount the sensor high enough not to see the floor, and keep the servo's wires free to swing.

Troubleshooting

  • The wheels never turn: the L298N's enable jumpers must be off, and START must be pressed on the dashboard.
  • The distance is always 400 cm: no echo; check TRIG and ECHO and the sensor's 5 V.
  • It turns the wrong way: swap the RIGHT and LEFT angles if the servo is mounted the other way round.
  • It hits obstacles: raise STOP_CM or lower the cruise speed; a faster robot needs more room to stop.
  • No dashboard: the ESP32 joins TEP-WiFi about three seconds after the start; press Go again.

Limitations of the Simulation

  • The HC-SR04, the SG90, the L298N and the TT motors are our libraries' models, built from their datasheets and the parts' behaviour, not every detail of real parts.
  • There is no room in the simulation: the obstacle is placed with the HC-SR04 pop-up, so the distance does not change by itself as the robot drives or turns.
  • The turn is a time, not an angle; on a real robot it is tuned.
  • ESP32 is a product of Espressif Systems; this project is not made or endorsed by Espressif or by Labcenter.

So, that was all about the Obstacle Avoiding Robot using ESP32 and HC-SR04 - Proteus Simulation. I hope it helps you understand how an ultrasonic sensor measures distance, how a servo turns it into a head, how an L298N steers two wheels, and how a small state machine makes the robot decide, all tested in a simulation before you build the car. More popular projects with the ESP32 and the Raspberry Pi 5 are coming. If you have any questions, ask in the comments and I will help you out. Till the next tutorial, take care and have fun!