The ultrasonic sensor is the most popular way to measure distance and sense detection. Using sonar technology, it sends electromagnetic waves out (TRIG), any object in front of it reflects the waves back (ECHO) to the sensor. The sensor detects the time it takes for these waves to return back to the sensor. The amount of time that the wave comes back is used to determine distance.
The internal working of the sensor is as follows:
The HCSR04 is triggered by setting the TRIG pin HIGH. Once the burst is sent the ECHO pin will automatically go HIGH. The Echo pin will remain HIGH until the the burst hits the sensor AGAIN. You can calculate the distance to the object by keeping track of how long the ECHO pin stays HIGH. The time ECHO stays HIGH is the time the burst spent traveling.
Connect Echo to Arduino pin 2, then connect Trig to Arduino pin 3.
Install and Run code below. Open serial monitor on Arduino software. Put your hand close, then further away from sensor. The distance your hand is from the sensor will be displayed.
For more details go to: