const int trig = 5;
//connect echo pin of ultrasonic sensor to port 7
const int echo = 7;
//giving motor connections as follows
const int m1a = 8;
const int m1b = 9;
const int m2a = 12;
const int m2b = 13;
void setup()
{
// activate serial monitor
Serial.begin(9600);
// defining trig pin as output since it produces sound waves
pinMode(trig, OUTPUT);
// defining echo pin as input since it receives sound waves
pinMode(echo, INPUT);
// defining motor pins as outputs
pinMode(m1a, OUTPUT);
pinMode(m1b, OUTPUT);
pinMode(m2a, OUTPUT);
pinMode(m2b, OUTPUT);
}
void loop()
{
// define two variables to store time and distance
long duration, distance;
// code for producing sound waves from transmitter part of sensor
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// finding time using pulseIn function and assign it into the variable duration
duration = pulseIn(echo, HIGH); // in microsecond
// calculating distance by multiplying time and velocity (0.034 cm per microsecond)
// it is then divided by 2 since the wave has traveled twice the distance between the sensor and the obstacle
distance = duration * 0.034/2; //in cm
// print distance on serial monitor
Serial.println(distance);
// checking whether the distance is less than 20 cm (may be varied)
if (distance < 20)
{
// give command to take turn (left or right). Below code may vary according to the connection
digitalWrite(m1a, HIGH);
digitalWrite(m1b, LOW);
digitalWrite(m2a, LOW);
digitalWrite(m2b, HIGH);
}
// checking whether the distance is greater than or equal to 20 cm
else if (distance >= 20)
{
// give command to go straight. Below code may vary according to the connection
digitalWrite(m1a, HIGH);
digitalWrite(m1b, LOW);
digitalWrite(m2a, HIGH);
digitalWrite(m2b, LOW);
}
// giving a delay of one second
delay(1000);