Ultrasonic Sensor Example
Ultrasonic Sensor is often used to detect the presence of objects or to measure the distance of a body.
In this example we use the HC-SR04 Ultrasonic module to measure the distance of an object and we print these measures on Serial port.
This module includes ultrasonic transmitter, receiver and control circuit, it allows to detect the distance of an object from 2 cm up to 400 cm (4 m) with an accurancy of 3mm.
Here you can download the datasheet of HC-SR04 Ultrasonic Module.
- Arduino Board
- Ultrasonic Sensor
The HC-SR04 Ultrasonic Module has four pins: VCC, Trig, Echo and GND. Connect the Vcc to 5V board pin, Trig to the digital pin 9 and Echo to the digital pin 8 of the board, finally connect the GND pin to GND board pin.
In the first part of sketch we declare the variables used and define which pins are used to connect to the Ultrasonic Module.
In the setup function first we initialize the Serial comunication with the command Serial.begin(9600), after we define the trig as output and the echo as input through the function pinMode, finally we set the trig at LOW level with the command digitalWrite.
In the loop block we set the trig to HIGH and after 10 microsecond we set it again to the LOW level.
We read the time between trasmitting and receiving signal with the function pulseIn(Echo,HIGH) and we place it in the duration variable.
After we check this value, if it is greater or equal than 38000 microsecond on Serial monitor we view this phrase:out range; else we see the measure of distance expressed in centimeter and meter.
We calculate the distance dividing duration by 58.
Calculation of the distance:
distance = speed of sound * duration
the speed of sound is 343,4 m/s or 0,0343 cm/microsecond to the Temperature of 20°C.
distance = 0,0343 * duration
we divide for 2 because the duration is the time spent from ultrasonic signal to sending and returning:
distance = 0,0343 * duration/2
0,0343/2 = 0,01715 = 1/58,31
distance = duration/58,31
distance = duration/58
// Ultrasonic Sensor Example
duration = pulseIn(echo, HIGH);
distance = duration/58;