Tuesday, November 10, 2020

How to measure distance using Ultrasonic sensor|How to Find Distance using soundwaves? (Full tutorial)

In this post, we are going to use the Ultrasonic Sensor to build a distance sensor. The HC-SR04 ultrasonic sensor can be programmed to send out a ping using an ultrasonic transmitter, and then measure the time it takes to hear the echo of the ping come back to the receiver, after bouncing off a object body. Since we know the speed of sound we can calculate the distance to the sensor.

     The circuit uses the following Schematic:Circuit diagram

        Schematic for Connecting the HC-SR04 to an Arduino
 

In order to produce ultrasonic sound, we need to set the Trigger Pin on HIGH for 10 µs. That will send out a sonic burst which will travel at the speed of sound and it will be received in the Echo Pin. The Echo Pin will send the output the time in microseconds the sound wave traveled.


timing diagram
        An ultrasonic HC-SR04 timing diagram



ultrasnoic distance calculate


For example, if the object is 10 cm away from the sensor, and the speed of the sound is 340 m/s or 0.034 cm/µs the sound wave have to travel for about 294 microseconds. But the output will get from the Echo pin will be double that number because the sound wave needs to travel and bounce backward. So in order to get the distance of the object in cm we need to multiply the received travel time value from the echo pin by speed of sound that is 0.034 and divide it by 2.
 

 Click to  direct download full arduino file code 

download
  Arduino Code: (Copy the code from below  or directly downlod arduino file from above )

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* by Manikant savadatti
*
*
*/
// defines pins numbers
const int trig = 9;
const int echo = 10;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trig, OUTPUT); // trigPin as an Output
pinMode(echo, INPUT); // echoPin as an Input
Serial.begin(9600); // Starts the serial monitor
}
void loop() {
// Clears the trigPin
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echoPin,returns the sound travel time in microseconds
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}









ManiTesla.tech

Author & Editor

Innovator and Robotics enthusisast intrested in building robots and web development

0 comments:

Post a Comment

Ask Something