Table of Contents
Overview
Before building the robot, it is important to understand how the ultrasonic sensor works because this sensor will play an important role in obstacle detection. The basic principle behind the operation of an ultrasonic sensor is to record the time it takes for the sensor to transmit ultrasound and receive ultrasound after touching a surface. Then the distance is calculated using the formula. In this project, the widely available HC-SR04 ultrasonic sensor is used. To use this sensor, a similar approach described above will be followed.
So the Trig pin of the HC-SR04 is pulled high for at least 10 minutes. An audio packet is transmitted with 8 pulses of 40 kHz each.
The signal then hits the surface and comes back and is picked up by the Echo pin of the HC-SR04 receiver. The Echo pin had already gone up at the time of sending.
Components Required
- Arduino NANO or Uno (any version)
- HC-SR04 Ultrasonic Sensor
- LM298N Motor Driver Module
- 5V DC Motors
- Battery
- Wheels
- Chassis
- Jumper Wires
Bill of Materials
Circuit Diagram
Final Code
///// www.mevihub.com ////////////////////////
int TrigPin = 9; // trig pin of HC-SR04
int EchoPin = 10; // Echo pin of HC-SR04
int Rev_Lef_4 = 4; //REVerse motion of Left motor
int Fwd_Lef_5 = 5; //ForWarD motion of Left motor
int Rev_Rig_6 = 6; //REVerse motion of Right motor
int Fwd_Rig_7 = 7; //ForWarD motion of Right motor
long duration, distance;
void setup() {
Serial.begin(9600);
pinMode(Rev_Lef_4, OUTPUT); // set Motor pins as output
pinMode(Fwd_Lef_5, OUTPUT);
pinMode(Rev_Rig_6, OUTPUT);
pinMode(Fwd_Rig_7, OUTPUT);
pinMode(TrigPin, OUTPUT); // set trig pin as output
pinMode(EchoPin, INPUT); //set echo pin as input to capture reflected waves
digitalWrite(Fwd_Rig_7, HIGH);
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Fwd_Lef_5, HIGH);
digitalWrite(Rev_Lef_4, LOW);
}
void loop() {
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH); // send waves for 10 us
delayMicroseconds(10);
duration = pulseIn(EchoPin, HIGH); // receive reflected waves
distance = duration / 58.2; // convert to distance
Serial.println( distance);
if (distance <30)
{
digitalWrite(Fwd_Rig_7, LOW); //Stop
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Fwd_Lef_5, LOW);
digitalWrite(Rev_Lef_4, LOW);
delay(600);
digitalWrite(Fwd_Rig_7, LOW); //movebackword
digitalWrite(Rev_Rig_6, HIGH);
digitalWrite(Fwd_Lef_5, LOW);
digitalWrite(Rev_Lef_4, HIGH);
delay(500);
digitalWrite(Fwd_Rig_7, LOW); //Stop
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Fwd_Lef_5, LOW);
digitalWrite(Rev_Lef_4, LOW);
delay(600);
digitalWrite(Fwd_Rig_7, HIGH);
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Rev_Lef_4, LOW);
digitalWrite(Fwd_Lef_5, LOW);
delay(500);
digitalWrite(Fwd_Rig_7, LOW);
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Rev_Lef_4, LOW);
digitalWrite(Fwd_Lef_5, HIGH);
delay(500);
digitalWrite(Fwd_Rig_7, HIGH);
digitalWrite(Rev_Rig_6, LOW);
digitalWrite(Fwd_Lef_5, HIGH);
digitalWrite(Rev_Lef_4, LOW);
delay(100);
}
}