The distance sensor (also known as an ultrasonic sensor) is used for distance measurements. It can estimate distances from 2 cm to 400 cm, with an accuracy of 3mm. It’s the most widely used and least expensive distance sensor. There are others available that are much more accurate, but also much more expensive.
You can buy one here, or find it in this kit.
To measure distance, the ultrasonic sensor uses a signal sent from the Trigger terminal and received by the Echo terminal. The time it takes for the Echo terminal to receive the signal gives the distance between the sensor and the object.
Here’s how the ultrasonic sensor calculates the distance: Distance = (received signal * speed of sound) /2
The speed of sound in air is 340 m/s.
Let’s take a look at some common examples of how the HC-SR04 ultrasonic sensor is used.
To start operating the sensor, you need to install the HC-SR04 library on arduino :
Here is a diagram of the sensor wiring:
Here is an initial program to measure distance using the sensor:
It is possible to operate the ultrasonic sensor without using a library. To do so, we’ll have to calculate the echo duration ourselves, i.e. the time it takes for the ultrasonic sensor to receive the beam. Then we’ll calculate the distance between the transducer and the object.
To dispense with the library, you’ll need to add certain elements to your program.
First of all, you’ll need to start a 10 microsecond beam on the trig terminal in order to start the signal.
Here we can see that the signal is switched off and then on for 10 microseconds, then switched off a second time.
Retrieve the time it takes for the signal to return to the sensor: duree = pulseIn(echoPin, HIGH);
We then calculate this distance using the formula given above: Distance = (received signal * speed of sound) /2
Speed of sound in air: 340 m/s
Distance = duration*0.034/2 ;
Here’s the same code, but without using the library this time:
In the program below, the intensity of the LED changes according to the distance from the obstacle.
Its intensity is expressed as a percentage in the table below:
Here is the program with the library:
Here is the same code without the library:
We’re now going to connect our ultrasonic sensor to an RGB LED so that the color of the LED changes as the measured distance decreases. The aim is to create a small radar that would use the LED to indicate when we’re getting closer to an object or obstacle.
Here is the program with the library:
Here is the same program associated with the project without the library: