Human Following Robot Using Arduino and Ultrasonic Sensor

Submitted by Gourav Tak on

Working of Human Following Robot Using Arduino

In recent years, robotics has witnessed significant advancements, enabling the creation of intelligent machines that can interact with the environment. One exciting application of robotics is the development of human-following robots. These robots can track and follow a person autonomously, making them useful in various scenarios like assistance in crowded areas, navigation support, or even as companions. In this article, we will explore in detail how to build a human following robot using Arduino and three ultrasonic sensors, complete with circuit diagrams and working code. Also, check all the Arduino-based Robotics projects by following the link.

The working of a human following robot using Arduino code and three ultrasonic sensors is an interesting project. What makes this project particularly interesting is the use of not just one, but three ultrasonic sensors. This adds a new dimension to the experience, as we typically see humans following a robot built with one ultrasonic, two IR, and one servo motor.  This servo motor has no role in the operation and also adds unnecessary complications. So I removed this servo and the IR sensors and used 3 ultrasonic sensors. With ultrasonic sensors, you can measure distance and use that information to navigate and follow a human target. Here’s a general outline of the steps involved in creating such a robot.

 

 

Components Needed for Human Following Robot Using Arduino

  • Arduino UNO board ×1

  • Ultrasonic sensor ×3

  • L298N motor driver ×1

  • Robot chassis

  • BO motors ×2

  • Wheels ×2

  • Li-ion battery 3.7V ×2

  • Battery holder ×1

  • Breadboard

  • Ultrasonic sensor holder ×3

  • Switch and jumper wires

Human Following Robot Using Arduino Circuit Diagram

Here is the schematic diagram of a Human-following robot circuit.

Arduino Human Following Robot Circuit Diagram

This design incorporates three ultrasonic sensors, allowing distance measurements in three directions front, right, and left. These sensors are connected to the Arduino board through their respective digital pins. Additionally, the circuit includes two DC motors for movement, which are connected to an L298N motor driver module. The motor driver module is, in turn, connected to the Arduino board using its corresponding digital pins. To power the entire setup, two 3.7V li-ion cells are employed, which are connected to the motor driver module via a switch.

Overall, this circuit diagram showcases the essential components and connections necessary for the Human-following robot to operate effectively.

arduino human following robot circuit

Circuit Connection:

Arduino and HC-SR04 Ultrasonic Sensor Module:

HC-SR04 Ultrasonic sensor Module

  • Connect the VCC pin of each ultrasonic sensor to the 5V pin on the Arduino board.

  • Connect the GND pin of each ultrasonic sensor to the GND pin on the Arduino board.

  • Connect the trigger pin (TRIG) of each ultrasonic sensor to separate digital pins (2,4, and 6) on the Arduino board.

  • Connect the echo pin (ECHO) of each ultrasonic to separate digital pins (3,5, and 7) on the Arduino board.

Arduino and Motor Driver Module:

  • Connect the digital output pins of the Arduino (digital pins 8, 9, 10, and 11) to the appropriate input pins (IN1, IN2, IN3, and IN4) on the motor driver module.

  • Connect the ENA and ENB pins of the motor driver module to the onboard High state pin with the help of a female header.

  • Connect the OUT1, OUT2, OUT3, and OUT4 pins of the motor driver module to the appropriate terminals of the motors.

  • Connect the VCC (+5V) and GND pins of the motor driver module to the appropriate power (Vin) and ground (GND) connections on the Arduino.

Power Supply:

  • Connect the positive terminal of the power supply to the +12V input of the motor driver module.

  • Connect the negative terminal of the power supply to the GND pin of the motor driver module.

  • Connect the GND pin of the Arduino to the GND pin of the motor driver module.

Human Following Robot Using Arduino Code

Here is a simple 3 Ultrasonic sensor-based Human following robot using Arduino Uno code that you can use for your project.

Ultrsonic Sensors on Robot

This code reads the distances from three ultrasonic sensors (‘frontDistance’, ‘leftDistance’, and ‘rightDistance’). It then compares these distances to determine the sensor with the smallest distance. If the smallest distance is below the threshold, it moves the car accordingly using the appropriate motor control function (‘moveForward()’, ‘turnLeft()’, ‘turnRight()’). If none of the distances are below the threshold, it stops the motor using ‘stop()’.

In this section, we define the pin connections for the ultrasonic sensors and motor control. The S1Trig, S2Trig, and S3Trig, variables represent the trigger pins of the three ultrasonic sensors, while S1Echo, S2Echo, and S3Echo, represent their respective echo pins.

The LEFT_MOTOR_PIN1, LEFT_MOTOR_PIN2, RIGHT_MOTOR_PIN1, and RIGHT_MOTOR_PIN2 variables define the pins for controlling the motors.

The MAX_DISTANCE and MIN_DISTANCE_BACK variables set the thresholds for obstacle detection.

// Ultrasonic sensor pins
#define S1Trig 2
#define S2Trig 4
#define S3Trig 6
#define S1Echo 3
#define S2Echo 5
#define S3Echo 7
// Motor control pins
#define LEFT_MOTOR_PIN1 8
#define LEFT_MOTOR_PIN2 9
#define RIGHT_MOTOR_PIN1 10
#define RIGHT_MOTOR_PIN2 11
// Distance thresholds for obstacle detection
#define MAX_DISTANCE 40
#define MIN_DISTANCE_BACK 5

Make sure to adjust the values of ‘MIN_DISTANCE_BACK’ and ‘MAX_DISTANCE’ according to your specific requirements and the characteristics of your robot.

The suitable values for ‘MIN_DISTANCE_BACK’ and ‘MAX_DISTANCE’ depend on the specific requirements and characteristics of your human-following robot. You will need to consider factors such as the speed of your robot, the response time of the sensors, and the desired safety margin

Here are some general guidelines to help you choose suitable values.

‘MIN_DISTANCE_BACK’ This value represents the distance at which the car should come to a stop when an obstacle or hand is detected directly in front. It should be set to a distance that allows the car to back safely without colliding with the obstacle or hand. A typical value could be around 5-10 cm.

‘MAX_DISTANCE’ This value represents the maximum distance at which the car considers the path ahead to be clear and can continue moving forward. It should be set to a distance that provides enough room for the car to move without colliding with any obstacles or hands. If your hand and obstacles are going out of this range, the robot should be stop. A typical value could be around 30-50 cm.

These values are just suggestions, and you may need to adjust them based on the specific characteristics of your robot and the environment in which it operates.

These lines set the motor speed limits. ‘MAX_SPEED’ denotes the upper limit for motor speed, while ‘MIN_SPEED’ is a lower value used for a slight left bias. The speed values are typically within the range of 0 to 255, and can be adjusted to suit our specific requirements.

// Maximum and minimum motor speeds
#define MAX_SPEED 150
#define MIN_SPEED 75

The ‘setup()’ function is called once at the start of the program. In the setup() function, we set the motor control pins (LEFT_MOTOR_PIN1, LEFT_MOTOR_PIN2, RIGHT_MOTOR_PIN1, RIGHT_MOTOR_PIN2) as output pins using ‘pinMode()’ . We also set the trigger pins (S1Trig, S2Trig, S3Trig) of the ultrasonic sensors as output pins and the echo pins (S1Echo, S2Echo, S3Echo) as input pins. Lastly, we initialize the serial communication at a baud rate of 9600 for debugging purposes.

void setup() {
  // Set motor control pins as outputs
  pinMode(LEFT_MOTOR_PIN1, OUTPUT);
  pinMode(LEFT_MOTOR_PIN2, OUTPUT);
  pinMode(RIGHT_MOTOR_PIN1, OUTPUT);
  pinMode(RIGHT_MOTOR_PIN2, OUTPUT);
  //Set the Trig pins as output pins
  pinMode(S1Trig, OUTPUT);
  pinMode(S2Trig, OUTPUT);
  pinMode(S3Trig, OUTPUT);
  //Set the Echo pins as input pins
  pinMode(S1Echo, INPUT);
  pinMode(S2Echo, INPUT);
  pinMode(S3Echo, INPUT);
  // Initialize the serial communication for debugging
  Serial.begin(9600);
}

This block of code consists of three functions (‘sensorOne()’, ‘sensorTwo()’, ‘sensorThree()’) responsible for measuring the distance using ultrasonic sensors.

The ‘sensorOne()’ function measures the distance using the first ultrasonic sensor. It's important to note that the conversion of the pulse duration to distance is based on the assumption that the speed of sound is approximately 343 meters per second. Dividing by 29 and halving the result provides an approximate conversion from microseconds to centimeters.

The ‘sensorTwo()’ and ‘sensorThree()’ functions work similarly, but for the second and third ultrasonic sensors, respectively.

// Function to measure the distance using an ultrasonic sensor
int sensorOne() {
  //pulse output
  digitalWrite(S1Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(S1Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(S1Trig, LOW);
  long t = pulseIn(S1Echo, HIGH);//Get the pulse
  int cm = t / 29 / 2; //Convert time to the distance
  return cm; // Return the values from the sensor
}
//Get the sensor values
int sensorTwo() {
  //pulse output
  digitalWrite(S2Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(S2Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(S2Trig, LOW);
  long t = pulseIn(S2Echo, HIGH);//Get the pulse
  int cm = t / 29 / 2; //Convert time to the distance
  return cm; // Return the values from the sensor
}
//Get the sensor values
int sensorThree() {
  //pulse output
  digitalWrite(S3Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(S3Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(S3Trig, LOW);
  long t = pulseIn(S3Echo, HIGH);//Get the pulse
  int cm = t / 29 / 2; //Convert time to the distance
  return cm; // Return the values from the sensor
}

In this section, the ‘loop()’ function begins by calling the ‘sensorOne()’, ‘sensorTwo()’, and ‘sensorThree()’ functions to measure the distances from the ultrasonic sensors. The distances are then stored in the variables ‘frontDistance’, ‘leftDistance’, and ‘rightDistance’.

Next, the code utilizes the ‘Serial’ object to print the distance values to the serial monitor for debugging and monitoring purposes.

void loop() {
  int frontDistance = sensorOne();
  int leftDistance = sensorTwo();
  int rightDistance = sensorThree();
  Serial.print("Front: ");
  Serial.print(frontDistance);
  Serial.print(" cm, Left: ");
  Serial.print(leftDistance);
  Serial.print(" cm, Right: ");
  Serial.print(rightDistance);
  Serial.println(" cm");

In this section of code condition checks if the front distance is less than a threshold value ‘MIN_DISTANCE_BACK’ that indicates a very low distance. If this condition is true, it means that the front distance is very low, and the robot should move backward to avoid a collision. In this case, the ‘moveBackward()’ function is called.

if (frontDistance < MIN_DISTANCE_BACK) {
    moveBackward();
    Serial.println("backward");

If the previous condition is false, this condition is checked. if the front distance is less than the left distance, less than the right distance, and less than the ‘MAX_DISTANCE’ threshold. If this condition is true, it means that the front distance is the smallest among the three distances, and it is also below the maximum distance threshold. In this case, the ‘moveForward()’ function is called to make the car move forward.

else if (frontDistance < leftDistance && frontDistance < rightDistance && frontDistance < MAX_DISTANCE) {
    moveForward();
    Serial.println("forward");

If the previous condition is false, this condition is checked. It verifies if the left distance is less than the right distance and less than the ‘MAX_DISTANCE’ threshold. This condition indicates that the left distance is the smallest among the three distances, and it is also below the minimum distance threshold. Therefore, the ‘turnLeft()’ function is called to make the car turn left.

else if (leftDistance < rightDistance && leftDistance < MAX_DISTANCE) {
    turnLeft();
    Serial.println("left");

If neither of the previous conditions is met, this condition is checked. It ensures that the right distance is less than the ‘MAX_DISTANCE’ threshold. This condition suggests that the right distance is the smallest among the three distances, and it is below the minimum distance threshold. The ‘turnRight()’ function is called to make the car turn right.

else if (rightDistance < MAX_DISTANCE) {
    turnRight();
    Serial.println("right");

If none of the previous conditions are true, it means that none of the distances satisfy the conditions for movement. Therefore, the ‘stop()’ function is called to stop the car.

 else {
    stop();
    Serial.println("stop");

In summary, the code checks the distances from the three ultrasonic sensors and determines the direction in which the car should move based on the 3 ultrasonic sensors with the smallest distance.

 

Important aspects of this Arduino-powered human-following robot project include:

  • Three-sensor setup for 360-degree human identification
  • Distance measurement and decision-making in real-time
  • Navigation that operates automatically without human assistance
  • Avoiding collisions and maintaining a safe following distance

 

 

Technical Summary and GitHub Repository 

Using three HC-SR04 ultrasonic sensors and an L298N motor driver for precise directional control, this Arduino project shows off the robot's ability to track itself. For simple replication and modification, the full source code, circuit schematics, and assembly guidelines are accessible in our GitHub repository. To download the Arduino code, view comprehensive wiring schematics, and participate in the open-source robotics community, visit our GitHub page.

Code Schematics Download Icon

 

Frequently Asked Questions

⇥ How does an Arduino-powered human-following robot operate?
Three ultrasonic sensors are used by the Arduino-powered human following robot to determine a person's distance and presence. After processing this data, the Arduino manages motors to follow the identified individual while keeping a safe distance.

⇥ Which motor driver is ideal for an Arduino human-following robot?
The most widely used motor driver for Arduino human-following robots is the L298N. Additionally, some builders use the L293D motor driver shield, which connects to the Arduino Uno directly. Both can supply enough current for small robot applications and manage 2-4 DC motors.

⇥ Is it possible to create a human-following robot without soldering?
Yes, you can use motor driver shields that connect straight to an Arduino, breadboards, and jumper wires to construct a human-following robot. For novices and prototyping, this method is ideal.

⇥ What uses do human-following robots have in the real world?
Shopping cart robots in malls, luggage-carrying robots in airports, security patrol robots, elderly care assistance robots, educational demonstration robots, and companion robots that behave like pets are a few examples of applications.

 

Conclusion

This human following robot using Arduino project and three ultrasonic sensors is an exciting and rewarding project that combines programming, electronics, and mechanics. With Arduino’s versatility and the availability of affordable components, creating your own human-following robot is within reach.

Human-following robots have a wide range of applications in various fields, such as retail stores, malls, and hotels, to provide personalized assistance to customers. Human-following robots can be employed in security and surveillance systems to track and monitor individuals in public spaces. They can be used in Entertainment and events, elderly care, guided tours, research and development, education and research, and personal robotics.

They are just a few examples of the applications of human-following robots. As technology advances and robotics continues to evolve, we can expect even more diverse and innovative applications in the future.

Explore Practical Projects Similar To Robots Using Arduino

Explore a range of hands-on robotics projects powered by Arduino, from line-following bots to obstacle-avoiding vehicles. These practical builds help you understand sensor integration, motor control, and real-world automation techniques. Ideal for beginners and hobbyists, these projects bring theory to life through interactive learning.

 Simple Light Following Robot using Arduino UNO

Simple Light Following Robot using Arduino UNO

Today, we are building a simple Arduino-based project: a light-following robot. This project is perfect for beginners, and we'll use LDR sensor modules to detect light and an MX1508 motor driver module for control. By building this simple light following robot you will learn the basics of robotics and how to use a microcontroller like Arduino to read sensor data and control motors.

Line Follower Robot using Arduino UNO: How to Build (Step-by-Step Guide)

Line Follower Robot using Arduino UNO: How to Build (Step-by-Step Guide)

This step-by-step guide will show you how to build a professional-grade line follower robot using Arduino UNO, with complete code explanations and troubleshooting tips. Perfect for beginners and intermediate makers alike, this project combines hardware interfacing, sensor calibration, and motor control fundamentals.

Have any question related to this Article?

How to Learn Robotics Without Any Hardware (Best Free Simulators in 2026)

Submitted by Soundarya on

When I was in college, all I wanted to do was build robots. I built line followers, wall followers and small robots with ultrasonic sensors, and I would happily spend whole weekends on each one. What I did not have was money. Every sensor and every motor driver meant saving up for weeks, so I could only build a small part of what I wanted to try.
After I got my first job, that problem flipped. For the first time I could order components whenever I wanted, and I did. I bought a lot of them, and many turned out to be the wrong ones. One example still stays with me. For a small robot, I bought micro metal gear motors with a high RPM because I wanted it to be fast. Once everything was mounted, the robot weighed more than those motors had the torque to carry, and it barely moved. I had to strip out parts and make the circuit smaller just to get it running. I had picked the motor for speed and never checked torque against weight. Looking back, I was buying parts before I understood what my robot actually needed.
That is why I now tell anyone starting to learn robotics without hardware first. Today you can wire circuits, program boards, drive complete robots and even move robot arms on a normal laptop, for free. By the time you buy your first parts, you will know exactly which ones you need and why. Here is how I would start if I were doing it again.

Why Start in Software?

A simulator gives you instant feedback. If a wire goes to the wrong pin, nothing burns; you fix it and press run again. You can test an idea in five minutes instead of waiting five days for a courier. Most importantly, the code you write in a simulator, whether it is Arduino C++, Python or ROS 2, carries over to real hardware almost unchanged.

Tinkercad robot circuit

Image Source: Autodesk Tinkercad, circuit by codingwitht2 (Instructables) 

Simulation does have limits. It will not teach you soldering, loose jumper wires, a battery that drops voltage under load, or a sensor that gives noisy readings in sunlight. You will learn those later, on real parts. But by then you will be debugging the hardware, not the basics.

Tinkercad Circuits: Arduino in your Browser

Obstacle-avoiding robot in Tinkercad Circuits

Image source: Autodesk Tinkercad circuit by codingwitht2, Instructables 

Tinkercad Circuits from Autodesk is where I would send any complete beginner. It runs in the browser; it is free, and you only need an account. You drag an Arduino Uno, a breadboard and components onto the screen, wire them up, and write the code either in blocks or in normal Arduino text.
A good first project is a small obstacle-avoiding robot, because it shows the cycle every robot follows: sense, think and act. We will keep building on this same robot for the rest of the article.

StepWhat does it                                   In this project
SenseInput sensorAn ultrasonic distance sensor measures how far away the obstacle is
ThinkMicrocontrollerArduino Uno compares the distance with a limit and decides what to do
ActOutput actuatorsTwo DC motors drive the robot forward, or turn it left or right

In Tinkercad, place an Arduino Uno, an ultrasonic distance sensor, two hobby gear motors and an L293D motor driver, because the Arduino's pins cannot supply enough current to run motors directly. The code reads the distance continuously. If the path is clear, both motors run forward. If something is closer than about 20 cm, one motor reverses, and the robot turns away.
While the simulation runs, click the ultrasonic sensor and drag the object closer, then watch the motors change direction.
Along the way, you learn breadboard wiring, digital and PWM pins, how a motor driver works, and how to read sensor values on the serial monitor.
Tinkercad is limited to Arduino Uno-class boards and a fixed parts library, so you will outgrow it. That is exactly the point of a first tool.
Example project: How to Create a Virtual Simulation of Obstacle Avoidance Robot in Tinkercad (Instructables) - A three-step project with a video that builds and runs a virtual obstacle-avoiding robot in Tinkercad Circuits.

Wokwi: ESP32 and Raspberry Pi Pico without the board

ESP32 robot running in the Wokwi simulator

Image Source: Wokwi simulator (wokwi.com), project by sief-ali 

In Tinkercad, everything stays on one board. A real robot usually needs to talk to the outside world: send an alert to your phone, log its readings, or take commands. That is why the next step is the ESP32, which has built-in Wi-Fi and Bluetooth Low Energy. It is also a good point to try a second language: as well as Arduino C++, the ESP32 runs MicroPython.
Wokwi simulates ESP32, Raspberry Pi Pico, Arduino and STM32 boards in the browser, and you can program the ESP32 in either Arduino C++ or MicroPython. Its Wi-Fi simulation lets the virtual ESP32 connect to the internet using HTTP or MQTT. Bluetooth is not simulated yet, so BLE projects still need the real board.
Now rebuild the same robot on an ESP32 in Wokwi. The HC-SR04 still does the sensing, and the ESP32 now thinks. The first change is the motors. Wokwi cannot simulate DC motors; its motor parts are servos and stepper motors. So the two wheels become stepper motors, each with an A4988 driver.
This turns out to be a useful lesson. A stepper motor moves a fixed angle for every step, typically 1.8 degrees, or 200 steps per turn. Count the steps, and you know exactly how far each wheel has travelled:
                                                                   d = (N_steps / 200) × π × D_wheel
Working out where a robot is from how much its wheels have turned is called odometry, and you will meet it again with TurtleBot3 later in this article.
Next, add an MPU6050, which combines a 3-axis accelerometer and a 3-axis gyroscope. From it you can read the robot's orientation (how much it is tilted) and its angular velocity (how fast it is turning). Adding up the turn rate over time tells you which way the robot is facing, so you can check whether it really turned as much as you commanded. Show the distance to the nearest obstacle, what the robot is doing (driving or turning) and its heading on an SSD1306 OLED display.
Finally, put it online. Wokwi's virtual ESP32 connects through a built-in guest Wi-Fi network, so when the HC-SR04 detects an obstacle, the ESP32 can send an alert to the Blynk app on your phone, along with the latest orientation readings. Write it first in Arduino C++, then try rewriting it in MicroPython to compare the two.
By the end, your robot senses, decides, moves, knows how far it has gone and reports to your phone, and you still have not spent a rupee.
Example project: How to Simulate ESP32 Projects Online for Free (Hackster). A step-by-step guide from the Wokwi team that starts a new ESP32 project in Wokwi and walks through the editor, the parts and the simulation controls.

Webots: your first complete robot simulator

Image source: Cyberbotics, Webots

Tinkercad and Wokwi simulate circuits. Webots simulates whole robots: wheels, motors, sensors, physics and the room they drive in. It is free and open source, runs on Windows, Linux and macOS, and comes with a large library of ready robot models, from the small e-puck to TurtleBot3 and industrial arms. You write the robot's controller in C, C++, Python, Java, MATLAB or ROS.
Webots also runs comfortably on a normal laptop, which is why I suggest it before Gazebo. Open one of the sample worlds, pick the e-puck, and open its controller file. Within ten minutes you are changing real robot code and watching the result.
Example project: Create and Play Your First Robot Program using Webots (Medium) -A short project that writes your first controller for the e-puck and makes it move, and the next part of the series adds simple obstacle avoidance.
 

ROS 2 and Gazebo: how real robots are programmed

TurtleBot3 in Gazebo (left) building a map with SLAM, shown in RViz (right)

Image source: ROBOTIS, TurtleBot3 SLAM simulation in Gazebo 

Once you are comfortable moving a simulated robot, it is time to learn ROS 2, the Robot Operating System. Despite the name, it is not an operating system. It is a framework that lets the different parts of a robot, such as the LiDAR driver, the mapping code and the motor controller, run as separate programs called nodes and talk to each other through topics. Most robotics companies and research labs build on it, and it is what I teach in my ROS 2 course on Circuit Digest.
Start with turtlesim, a tiny 2D turtle that you move from the keyboard. It looks simple, but it teaches you nodes, topics, publishers and subscribers, which are the core of every ROS 2 robot.
Then move to Gazebo with a TurtleBot3. ROBOTIS, the company behind TurtleBot3, provides ready simulation packages for ROS 2 Jazzy with Gazebo Harmonic. You launch a house world, drive the robot from the keyboard, and watch its simulated LiDAR scan in RViz. TurtleBot3 also publishes its odometry on a topic called /odom, the same idea you worked out by counting stepper steps in Wokwi. A few commands later, you can build a map of the house using SLAM, which is the same workflow I am using for my real Bumper-Bot.
ROS 2 Jazzy runs best on Ubuntu 24.04. If you use Windows, you can run it inside WSL or set up a dual boot.
Example project: ROS 2 Jazzy obstacle avoidance for TurtleBot3 in Gazebo (GitHub) -A Python ROS 2 node that splits the LiDAR scan into front, left and right zones and steers the TurtleBot3 away from obstacles, with setup steps for Ubuntu 24.04 on WSL.
 

Two first projects: obstacle avoidance and line following

The e-puck robot following a black line in Webots

Image source: Felipe N. Martins, Robotics Simulation Labs (Webots) 

These are the two projects every robotics beginner builds on real hardware, so build them in simulation first.
For obstacle avoidance, the e-puck in Webots is ideal. It has eight infrared distance sensors around its body, named ps0 to ps7. The two front sensors are ps0 and ps7. It is the same sense, think, act loop as your Tinkercad robot, now with real physics. The logic is simple: if something is close on the right, turn left, and if it is close on the left, turn right.
from controller import Robot

robot = Robot()
timestep = int(robot.getBasicTimeStep())
MAX_SPEED = 6.28
sensors = [robot.getDevice(f"ps{i}") for i in range(8)]
for s in sensors:
   s.enable(timestep)
left = robot.getDevice("left wheel motor")
right = robot.getDevice("right wheel motor")
for m in (left, right):
   m.setPosition(float("inf"))
while robot.step(timestep) != -1:
   values = [s.getValue() for s in sensors]
   right_obstacle = values[0] > 80 or values[1] > 80
   left_obstacle = values[6] > 80 or values[7] > 80
   left_speed = right_speed = 0.5 * MAX_SPEED
   if left_obstacle:
       left_speed, right_speed = 0.5 * MAX_SPEED, -0.5 * MAX_SPEED
   elif right_obstacle:
       left_speed, right_speed = -0.5 * MAX_SPEED, 0.5 * MAX_SPEED
   left.setVelocity(left_speed)
   right.setVelocity(right_speed)

The threshold of 80 is a raw sensor value, so try changing it and see how early the robot reacts. In Gazebo, you can do the same thing with the TurtleBot3's LiDAR by splitting the scan into left, front and right zones.
For line following, add ground sensors to the e-puck and draw a black line on the floor of your world. When the left sensor sees the line, steer left; when the right one sees it, steer right. It is exactly the logic you would use with IR sensors on a real line follower, one of the robots I built in college.
Example project: Line-follower with State Machine (Robotics Simulation Labs) -This lab uses the e-puck's ground sensors in a Webots sample world to follow a line, after first working through obstacle avoidance with its distance sensors.

Moving a robot arm in simulation

A robot arm planning a motion with MoveIt 2 in RViz

Image source: MoveIt documentation, PickNik Robotics

Robot arms are expensive, which makes them the best reason to use a simulator. Webots includes several industrial arm models, such as the Universal Robots UR series and the Franka Emika Panda, and each joint is just a motor you can command from code.
Start with forward kinematics: set each joint to an angle and see where the end of the arm ends up. For a simple two-link arm with link lengths L1 and L2 and joint angles θ1 and θ2, the end point is:
x = L1 cos θ1 + L2 cos(θ1 + θ2)
y = L1 sin θ1 + L2 sin(θ1 + θ2)
Then try it the other way round, which is inverse kinematics: pick a point and work out the joint angles that reach it. This is the maths behind every pick-and-place robot, and it is far easier to learn when a wrong answer only means a virtual arm swinging the wrong way.
If you are already using ROS 2, the next step is MoveIt 2, which plans arm movements and shows them in RViz. It works the same way with a simulated arm as with a real one.
Example project: How to Create Your First C++ MoveIt 2 Project - A small "Hello World" project that moves the gripper of a simulated myCobot arm to a position you choose, shown in Gazebo and RViz.

NVIDIA Isaac Sim: where it fits

Many humanoid robots training in parallel in NVIDIA Isaac Sim

Image source: NVIDIA Technical Blog 

You will see Isaac Sim everywhere in robotics news, especially around humanoids and robot learning. It produces very realistic scenes and is used to train robots with AI, for example by generating synthetic camera data or running thousands of training attempts in parallel.
The catch is hardware. NVIDIA's current requirements list a GeForce RTX 4080 with 16 GB of VRAM and 32 GB of RAM as the minimum, so most student laptops cannot run it. My advice is to learn the ideas behind it now, and come back to it once you are comfortable with Webots or Gazebo and have access to a suitable GPU, whether at college, at work or in the cloud.
Example project (for later): MoveIt 2 in Isaac Sim (NVIDIA docs) - NVIDIA's tutorial runs a robot arm scene in Isaac Sim with MoveIt 2, so it connects to what you learned in the arm section.

Which simulator should you start with?

Which simulator first: Tinkercad, Wokwi, Webots, ROS 2 with Gazebo, then Isaac Sim

Image Source: Autodesk Tinkercad (codingwitht2), Wokwi, Cyberbotics, ROBOTIS, NVIDIA (same sources as the images above)

If you are completely new, go in this order: Tinkercad, then Wokwi, then Webots, then ROS 2 with Gazebo. Leave Isaac Sim for later.

ToolBest forRuns onCostWhat you need
Tinkercad CircuitsBasic electronics and Arduino programmingBrowserFreeAny laptop and internet
WokwiESP32, Raspberry Pi Pico, STM32 and MicroPython projectsBrowserFree plan, paid plans for extra featuresAny laptop and internet
WebotsComplete robots, beginner-friendlyWindows, Linux, macOSFree and open sourceA normal laptop
ROS 2 with GazeboHow real robots are programmed: SLAM, navigation, armsUbuntu 24.04 (WSL on Windows)Free and open sourceA normal laptop; a dedicated GPU helps
NVIDIA Isaac SimRealistic simulation and robot learning with AIUbuntu or Windows 11Free downloadRTX 4080-class GPU, 16 GB VRAM, 32 GB RAM

When to buy your first parts

Buy hardware once your simulated robot can avoid obstacles and follow a line, and once you understand why each part is there. At that point, a small starter set covers almost everything you have practised: an Arduino Uno or ESP32, two geared DC motors with wheels, a motor driver, an ultrasonic sensor, a pair of IR line sensors and a battery pack. In other words, the same robot you have already built in Tinkercad and Wokwi.

When to buy parts: the same robot, already built in simulation, and the six parts to buy

Image Source: Autodesk Tinkercad, circuit by codingwitht2 (Instructables)

Most of your simulation code will move across with small changes to PINs and sensor thresholds. Simulators also make you think about the things I skipped. In Webots and Gazebo, every motor has a maximum torque, so a robot that is too heavy for its motors simply will not move, long before you have paid for anything. The difference from my own first shopping spree is that this time you will be buying parts you already know how to use.
 

Have any question related to this Article?