How to make an obstacle avoiding Robot using an Ultrasonic sensor?

Rushank Shah
2 min readMay 18, 2021

--

What is an Ultrasonic Sensor?

Ultrasonic transducers and ultrasonic sensors are devices that generate or sense ultrasound energy. They can be divided into three broad categories: transmitters, receivers and transceivers. Transmitters convert electrical signals into ultrasound, receivers convert ultrasound into electrical signals, and transceivers can both transmit and receive ultrasound.

OK, that’s all for theory. Now let’s build the Robot itself.

Let’s start building 🤓

But before that. What all components will you need?

Here is a list of all the components you will need to create this project:

  1. Ultrasonic Sensor (HC-SR04 preferred)
  2. Arduino Uno (Preferrable, but any would work)
  3. Motor Driver (L293d)
  4. A robot with 2 or 4 motors (DC Motors)

So now we have all the components. What’s next? It’s always a good idea to first understand the logic we are going to implement before building the stuff itself. So let’s start with the logic!

Before building the logic, let’s define our aim again. We want to build an obstacle avoiding robot, Right? In the literal sense, it means that the robot should change its path whenever it encounters an obstacle. So the simplest logic is to make it turn one way around till it senses there is an obstacle in its path. This is our logic! Once the robot encounters an obstacle, we will turn it around in one direction (in our case left) and continue turning it unless the minimum threshold distance is reached. This will keep the robot safe and it will never hit an obstacle.

So here is the code that will essentially build this logic:

const int RMF = 3;
const int RMB = 4;
const int LMF = 5;
const int LMB = 6;
const int trigPin = 9;
const int echoPin = 8;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode (RMF, OUTPUT);
pinMode (RMB, OUTPUT);
pinMode (LMF, OUTPUT);
pinMode (LMB, OUTPUT);
}
long duration, distance;
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration / 58.2;
if (distance < 20) {
digitalWrite(RMF, HIGH);
digitalWrite(RMB, LOW);
digitalWrite(LMF, LOW);
digitalWrite(LMB, HIGH);
delay(1000);
} else {
digitalWrite(RMF, HIGH);
digitalWrite(RMB, LOW);
digitalWrite(LMF, HIGH);
digitalWrite(LMB, LOW);
}
}

You can find the code over here.

Here, I have kept the threshold value to 20 cm but you can keep as much as you want. Just change the number in place of 20 and it should work.

Here is the circuit diagram to make it work:

Circuit Diagram

You can replace the batteries with the ones that work for your motor.

That’s it. Now you can build your own obstacle avoiding bot.

Happy Coding :)

--

--

Responses (1)