Chapter 21 Ultrasonic Ranging

In this chapter, we learn a module which use ultrasonic to measure distance, HC SR04.

Project 21.1 Ultrasonic Ranging

In this project, we use ultrasonic ranging module to measure distance, and print out the data in the terminal.

Component List

ESP32-WROVER x1

Chapter01_00

GPIO Extension Board x1

Chapter01_01

Breadboard x1

Chapter01_02

HC SR04 x1

Chapter21_00

Jumper F/M x4

Chapter20_01

Component Knowledge

The ultrasonic ranging module uses the principle that ultrasonic waves will be sent back when encounter obstacles. We can measure the distance by counting the time interval between sending and receiving of the ultrasonic waves, and the time difference is the total time of the ultrasonic wave’s journey from being transmitted to being received. Because the speed of sound in air is a constant, about v=340m/s, we can calculate the distance between the ultrasonic ranging module and the obstacle: s=vt/2.

../../../_images/Chapter21_01.png

The HC-SR04 ultrasonic ranging module integrates both an ultrasonic transmitter and a receiver. The transmitter is used to convert electrical signals (electrical energy) into high frequency (beyond human hearing) sound waves (mechanical energy) and the function of the receiver is opposite of this. The picture and the diagram of the HC SR04 ultrasonic ranging module are shown below:

Chapter21_00

Chapter21_02

Pin description:

Pin

Description

VCC

power supply pin

Trig

trigger pin

Echo

Echo pin

GND

GND

Technical specs:

Working voltage: 5V

Working current: 12mA

Minimum measured distance: 2cm

Maximum measured distance: 200cm

Instructions for use: output a high-level pulse in Trig pin lasting for least 10us, the module begins to transmit ultrasonic waves. At the same time, the Echo pin is pulled up. When the module receives the returned ultrasonic waves from encountering an obstacle, the Echo pin will be pulled down. The duration of high level in the Echo pin is the total time of the ultrasonic wave from transmitting to receiving, s=vt/2.

../../../_images/Chapter21_03.png

Circuit

Note that the voltage of ultrasonic module is 5V in the circuit.

Schematic diagram

Chapter21_04

Hardware connection

If you need any support, please feel free to contact us via: support@freenove.com

Chapter21_05

Sketch

Sketch_21.1_Ultrasonic_Ranging

../../../_images/Chapter21_06.png

Download the code to ESP32-WROVER, open the serial port monitor, set the baud rate to 115200 and you can use it to measure the distance between the ultrasonic module and the object. As shown in the following figure:

../../../_images/Chapter21_07.png

The following is the program code:

 1/**********************************************************************
 2  Filename    : Ultrasonic Ranging
 3  Description : Use the ultrasonic module to measure the distance.
 4  Auther      : www.freenove.com
 5  Modification: 2024/06/19
 6**********************************************************************/
 7#define trigPin 13 // define TrigPin
 8#define echoPin 14 // define EchoPin.
 9#define MAX_DISTANCE 700 // Maximum sensor distance is rated at 400-500cm.
10//timeOut= 2*MAX_DISTANCE /100 /340 *1000000 = MAX_DISTANCE*58.8
11float timeOut = MAX_DISTANCE * 60; 
12int soundVelocity = 340; // define sound speed=340m/s
13
14void setup() {
15  pinMode(trigPin,OUTPUT);// set trigPin to output mode
16  pinMode(echoPin,INPUT); // set echoPin to input mode
17  Serial.begin(115200);   // Open serial monitor at 115200 baud to see ping results.
18}
19
20void loop() {
21  delay(100); // Wait 100ms between pings (about 20 pings/sec). 
22  Serial.printf("Distance: ");
23  Serial.print(getSonar()); // Send ping, get distance in cm and print result 
24  Serial.println("cm");
25}
26
27float getSonar() {
28  unsigned long pingTime;
29  float distance;
30  // make trigPin output high level lasting for 10μs to triger HC_SR04
31  digitalWrite(trigPin, HIGH); 
32  delayMicroseconds(10);
33  digitalWrite(trigPin, LOW);
34  // Wait HC-SR04 returning to the high level and measure out this waitting time
35  pingTime = pulseIn(echoPin, HIGH, timeOut); 
36  // calculate the distance according to the time
37  distance = (float)pingTime * soundVelocity / 2 / 10000; 
38  return distance; // return the distance value
39}

First, define the pins and the maximum measurement distance.

1#define trigPin 13 // define TrigPin
2#define echoPin 14 // define EchoPin.
3#define MAX_DISTANCE 700 // Maximum sensor distance is rated at 400-500cm.

If the module does not return high level, we cannot wait for this forever, so we need to calculate the time period for the maximum distance, that is, time Out. timeOut= 2*MAX_DISTANCE/100/340*1000000. The result of the constant part in this formula is approximately 58.8.

1float timeOut = MAX_DISTANCE * 60; 

Subfunction getSonar () function is used to start the ultrasonic module to begin measuring, and return the measured distance in cm units. In this function, first let trigPin send 10us high level to start the ultrasonic module. Then use pulseIn () to read the ultrasonic module and return the duration time of high level. Finally, the measured distance according to the time is calculated.

 1float getSonar() {
 2  unsigned long pingTime;
 3  float distance;
 4  // make trigPin output high level lasting for 10μs to triger HC_SR04
 5  digitalWrite(trigPin, HIGH); 
 6  delayMicroseconds(10);
 7  digitalWrite(trigPin, LOW);
 8  // Wait HC-SR04 returning to the high level and measure out this waitting time
 9  pingTime = pulseIn(echoPin, HIGH, timeOut); 
10  // calculate the distance according to the time
11  distance = (float)pingTime * soundVelocity / 2 / 10000; 
12  return distance; // return the distance value
13}

About function pulseIn():

int pulseIn(int pin, int level, int timeout);

pin : the number of the Arduino pin on which you want to read the pulse. Allowed data types: int.

value : type of pulse to read: either HIGH or LOW. Allowed data types: int.

timeout (optional): the number of microseconds to wait for the pulse to start; default is one second.

Project 21.2 Ultrasonic Ranging

Component List and Circuit

Component List and Circuit are the same as the previous section.

Sketch

How to install the library

We use the third party library UltrasonicSensor. If you haven’t installed it yet, please do so before learning.

The steps to add third-party Libraries are as follows: open arduino -> Sketch -> Include library -> Manage libraries. Enter “UltrasonicSensor” in the search bar and select “UltrasonicSensor” for installation.

Refer to the following operations:

../../../_images/Chapter21_08.png ../../../_images/Chapter21_09.png

Sketch_21.2_Ultrasonic_Ranging

../../../_images/Chapter21_10.png

Download the code to ESP32-WROVER, open the serial port monitor, set the baud rate to 115200. Use the ultrasonic module to measure distance. As shown in the following figure:

../../../_images/Chapter21_11.png

The following is the program code:

 1/**********************************************************************
 2  Filename    : Ultrasonic Ranging
 3  Description : Use the ultrasonic module to measure the distance.
 4  Auther      : www.freenove.com
 5  Modification: 2024/06/19
 6**********************************************************************/
 7#include <UltrasonicSensor.h>
 8
 9UltrasonicSensor ultrasonic(13, 14);
10
11void setup() {
12  Serial.begin(115200);
13
14  int temperature = 22;
15  ultrasonic.setTemperature(temperature);
16}
17
18void loop() {
19  int distance = ultrasonic.distanceInCentimeters();
20  Serial.printf("Distance: %dcm\n",distance);
21  delay(300);
22}

First, add UltrasonicSensor library.

1#include <UltrasonicSensor.h>

Define an ultrasonic object and associate the pins.

1UltrasonicSensor ultrasonic(13, 14);

Set the ambient temperature to make the module measure more accurately.

1ultrasonic.setTemperature(temperature);

Use the distanceInCentimeters function to get the distance measured by the ultrasound and print it out through the serial port.

1void loop() {
2  int distance = ultrasonic.distanceInCentimeters();
3  Serial.printf("Distance: %dcm\n",distance);
4  delay(300);
5}

Reference

class UltrasonicSensor

class UltrasonicSensor must be instantiated when used, that is, define an object of Servo type, for example:

UltrasonicSensor ultrasonic(13, 14);

setTemperature(value): The speed of sound propagation is different at different temperatures. In order to get more accurate data, this function needs to be called. value is the temperature value of the current environment.

distanceInCentimeters(): The ultrasonic distance acquisition function returns the value in centimeters.

distanceInMillimeters(): The ultrasonic distance acquisition function returns the value in millimeter.