On this project we will evaluate one of the most popular Proximity Sensors in the Arduino world, the HC-SR04 Ultrasonic Range Sensor, we will learn all we need to learn about it and in future projects we will be comparing it to other types of proximity sensors in the market.
The HC-SR04 uses ultrasound sonar to measure the distance to an object. The SR04 consists of one ultrasonic transmitter, one receiver, and a control circuit. The transmitter emits a high frequency ultrasonic sound, which bounce off solid objects while the receiver listens for any return echo. That echo is then processed by the control circuit to calculate the time difference between the sonic burst being transmitted and received. This time difference is called a Pulse Width and it will help calculate how far, or close, an object is.
Sensor's Pin configuration:
Pin
Function
VCC
5V, input power
TRIG
Trigger
ECHO
Echo
GND
Ground
To initiate the process of sensing for objects, the software will trigger a sonic burst by rising the voltage on the "Trigger" pin, and after a few milliseconds, it will lower the voltage to zero and wait for a sonic burst bouncing off any close objects, this sonic wave is, in turn, relaid to the controller board through the "Echo" pin.
So the time it takes for the triggered sonic pulse to travel to an object and get back to the sensor divided by two (because we only care about the time coming back) and multiplied by the Speed of Sound will give us the distance to the bouncing object.
Distance = (Speed of Sound * Time)/2
Where speed of sound at sea level is equal 343 meters/s or 34,300 cm/s (1,125 feet/s or 13,504 in/s)
Therefore, Distance = (17,150 * Time) expressed in centimetersor, Distance = (6,752 * Time) expressed in inches
Table 1 - Device Technical Specifications:
###
Name
Description
1
Voltage
DC 5 V
2
Current
15mA
3
Frequency
40Hz
4
Max Range
4 meters
5
Min Range
2cm
6
Trigger Angle
15 degrees
7
Trigger Input Signal
10uS TTL pulse
8
Echo Output Signal
TTL
9
Physical dimensions
45 x 20 x 15mm
You can get the all the code down below but observe this piece of code which is the heart of the Arduino Mega 2560 Controller program.
Observe how the Sensor's Trigger pin is rised to HIGH for 10microseconds then LOWered to zero followed by issuing the statement "pulseIn" which measures the Pulse Width via the Echo pin.