Hi guys in this tutorial we will see how to measure distance using Ultrasonic sensor with Arduino. So let’s get started. For doing this you will need

Ultrasonic sensor is a device which send out the sound wave and receiver receive the sound wave and what is time required for sound wave to come back at receiver is calculated and we get distance from this formula.

It is divided by 2 because sound wave goes and hit the surface then comeback to receiver so waves travelled two times the distance therefore we need to divide by two.

It is used in many application such as car parking sensor, liquid level detection, counter, robotics application and obstacle detection.

##### sketch:
```#define trigPin 13
#define echoPin 12

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}```
##### Explanation:

Define trigger pin & echo pin. Serial.begin will initialize the screen. Set trigger pin for output & echo pin for input.

In loop function we will setup two variable in type of long which is duration & distance. Long which is 4 bytes in size and store 32 bit. It can hold very large number.

` long duration, distance;`

Trigger pin is low for 2 micro second then trigger pin is high for 10 micro second then again trigger pin is low for that iteration. PulseIn read the pulse either high or low on pin. It measure the time between high and low on echo pin. It gives time in microsecond. 1000 microsecond is equal to one millisecond.

```duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;```

Now come to the formula for speed of sound which equal to 343.5m/s at 20 degree Celsius we need to convert this in cm/microsecond so we should multiply it by 100 and divided by 1 million. So we get 0.03435 cm/microsecond. When we reciprocate it we got 29.1 and put this value in original formula and in place of time write duration. If you want distance in millimeter you can write 2.91 instead of 29.1 and change serial.println to mm.

if distance is equal to or greater than 200cm OR distance is equal to zero then it will print “out of range”. Else it will print distance and unit of distance that is cm. and it will delay the program for 500 millisecond.

```  if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);```

When I put my diary in front of sensor it is showing exact distance we can see on the scale.

Till then keep learning keep making 🙂

Categories: Arduino