DEV Community

Cover image for Accident Avoider Robot using Ultrasonic sensor
Rohith ND
Rohith ND

Posted on

Accident Avoider Robot using Ultrasonic sensor

In this blog, I will show you how to build an Accident Avoider Robot with an Ultrasonic sensor and an Arduino microcontroller.

accident avoider

Components required

  • Arudino UNO
  • HC-SR04 Ultrasonic sensor
  • Gear Motors
  • IC L293D

Arduino UNO

Arduino is an opensource electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs - light on a sensor , a finger on a button , or a twitter message - and turn it into an output - activating a motor , turning on a LED , publishing something online. To do so use the Arduino programming language (based on wiring) and the Arduino Software (IDE) based on processing.

HC-SR04 Ultrasonic sensor

The Ultrasonic Sensor HC-SR04 is a distance measuring sensor. It emits an ultrasound at 40 000 Hz (40kHz) that travels through the air and bounces back to the module if it encounters an object or obstacle. You can calculate the distance by taking the travel time and the speed of the sound into account.

Gear Motors

It is a DC motor with a gear box for decreasing the speed and increasing the torque and power . This type of motors is commonly used for robotic applications.

IC L293D

IC L293D is a dual H-bridge motor driver integrated circuit that can drive current of up to 600mA with voltage range of 4.5 to 36 volts.

l293d

Code

#define trigPin 3
#define echoPin 2
int leftmotor = 4;
int leftmotor1 = 5;
int rightmotor = 6;
int rightmotor1 = 7;

void setup()

{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  //MOTORS
  pinMode(leftmotor, OUTPUT);// M1
  pinMode(leftmotor1, OUTPUT);// M2
  pinMode(rightmotor, OUTPUT);// M3
  pinMode(rightmotor1, OUTPUT);// M4

}
void loop() {
  int duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 58);
  if (distance < 10)
  {
    digitalWrite(leftmotor, HIGH);//FORWARD
    digitalWrite(leftmotor1, LOW);
    digitalWrite(rightmotor, HIGH);
    digitalWrite(rightmotor1, LOW);
  }
  if (distance >= 10)
  {
    digitalWrite(leftmotor, LOW);//BACKWARD
    digitalWrite(leftmotor1, HIGH);
    digitalWrite(rightmotor, LOW);
    digitalWrite(rightmotor1, HIGH);
    delay(2000);
    digitalWrite(leftmotor, LOW);//RIGHT
    digitalWrite(leftmotor1, HIGH);
    digitalWrite(rightmotor, HIGH);
    digitalWrite(rightmotor1, LOW);
    delay(2000);
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)