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

Code

Move the program folder “Freenove_Ultimate_Starter_Kit_for_ESP32/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.

Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “21.1_Ultrasonic_Ranging” and double click “Ultrasonic_Ranging.py”.

21.1_Ultrasonic_Ranging

../../../_images/Chapter21_12.png

Click “Run current script”, you can use it to measure the distance between the ultrasonic module and the object. As shown in the following figure:

../../../_images/Chapter21_13.png

The following is the program code:

 1from machine import Pin
 2import time
 3
 4trigPin=Pin(13,Pin.OUT,0)
 5echoPin=Pin(14,Pin.IN,0)
 6
 7soundVelocity=340
 8distance=0
 9
10def getSonar():
11    trigPin.value(1)
12    time.sleep_us(10)
13    trigPin.value(0)
14    while not echoPin.value():
15        pass
16    pingStart=time.ticks_us()
17    while echoPin.value():
18        pass
19    pingStop=time.ticks_us()
20    pingTime=time.ticks_diff(pingStop,pingStart)
21    distance=pingTime*soundVelocity//2//10000
22    return int(distance)
23
24time.sleep_ms(2000)
25while True:
26    time.sleep_ms(500)
27    print('Distance: ', getSonar(), 'cm' )

Define the control pins of the ultrasonic ranging module.

1trigPin=Pin(13,Pin.OUT,0)
2echoPin=Pin(14,Pin.IN,0)

Set the speed of sound.

1soundVelocity=340
2distance=0

Subfunction getSonar() is used to start the Ultrasonic Module to begin measurements, and return the measured distance in centimeters. 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.

 1def getSonar():
 2    trigPin.value(1)
 3    time.sleep_us(10)
 4    trigPin.value(0)
 5    while not echoPin.value():
 6        pass
 7    pingStart=time.ticks_us()
 8    while echoPin.value():
 9        pass
10    pingStop=time.ticks_us()
11    pingTime=time.ticks_diff(pingStop,pingStart)
12    distance=pingTime*soundVelocity//2//10000
13    return int(distance)

Delay for 2 seconds and wait for the ultrasonic module to stabilize. Print data obtained from ultrasonic module every 500 milliseconds

1time.sleep_ms(2000)
2while True:
3    time.sleep_ms(500)
4    print('Distance: ', getSonar(), 'cm' )

Project 21.2 Ultrasonic Ranging

Component List and Circuit

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

Code

Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “21.2_Ultrasonic_Ranging”. Select “hcsr04.py”, right click your mouse to select “Upload to /”, wait for “hcsr04.py” to be uploaded to ESP32-WROVER and then double click “Ultrasonic_Ranging.py”.

Ultrasonic_Ranging

../../../_images/Chapter21_14.png

Click “Run current script”. Use the ultrasonic module to measure distance. As shown in the following figure:

../../../_images/Chapter21_15.png

The following is the program code:

 1from hcsr04 import SR04
 2import time
 3
 4SR=SR04(13,14)
 5
 6time.sleep_ms(2000)
 7try:
 8    while True:
 9        print('Distance: ',SR.distance(),'cm')
10        time.sleep_ms(500)
11except:
12    pass

Import hcsr04 module.

1from hcsr04 import SR04

Define an ultrasonic object and associate with the pins.

1SR=SR04(13,14)

Obtain the distance data returned from the ultrasonic ranging module.

1SR.distance()

Obtain the ultrasonic data every 500 milliseconds and print them out in “Shell”.

1while True:
2    print('Distance: ',SR.distance(),'cm')
3    time.sleep_ms(500)

Reference

Class hcsr04

Before each use of object SR04 , please add the statement “from hcsr04 import SR04” to the top of python file.

SR04(): Object of ultrasonic module. By default, trig pin is Pin(13) and echo pinis Pin(14).

distanceCM(): Obtain the distance from the ultrasonic to the measured object with the data type being int type, and the unit being cm.

distanceMM(): Obtain the distance from the ultrasonic to the measured object with the data type being int type, and the unit being mm.

distance(): Obtain the distance from the ultrasonic to the measured object with the data type being float type, and the unit being cm.