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.
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.
An ultrasonic HC-SR04 timing diagram
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
Arduino Code: (Copy the code from below or directly downlod arduino file from above )
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
pinMode(trig, OUTPUT); // trigPin as an Output
pinMode(echo, INPUT); // echoPin as an Input
Serial.begin(9600); // Starts the serial monitor
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
// 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);
0 comments:
Post a Comment
Ask Something