3.7 Ultrasonic Sensor

3.7.1 Overview

Ultrasonic sensor measures the distance of an object by sound waves. It boasts a transmitter and a receiver to emit sound waves and then measure the returned waves. The time difference between transmitting and receiving can be used to calculate the distance value. Beyond that, it is also used to detect the shape or presence of objects, build automatic doors, and measure flow rates and pressures.

3.7.2 Schematic Diagram

6-7

Working principle: Like bats, the ultrasonic sensor sends an ultrasonic signal with a high frequency that human cannot hear. If these signals encounter obstacles, they will immediately reflect back and be received by the sensor. After that, the distance between the sensor and the obstacle is calculated according to the time difference between signals transmitting and receiving.

Maximum detection distance: 3M

Minimum detection distance: 4cm

Detection angle: no greater than 15 degrees

3.7.4 Test Code

In Files, open 3-7-ultrasonic.py and click .

Code:

'''
 * Filename    : 3-7-ultrasonic
 * Thonny      : Thonny 4.1.4
 * Auther      : http//www.keyestudio.com
'''
from machine import Pin
import time

# define the control pin of the ultrasonic sensor
Trig = Pin(5, Pin.OUT) 
Echo = Pin(4, Pin.IN)

distance = 0 # define the initial value to 0
soundVelocity = 340 #Set the speed of sound.

# getDistance() measures the distance, Echo.value() reads the status of Echo pin. Use the timestamp function of the time module to calculate the high level of the Echo's duration pin, and calculate the measured distance based on the time and return the value.
def getDistance():
    # Trig pin maintains high level for 10us to enable to the ultrasonic sensor
    Trig.value(1)
    time.sleep_us(10)
    Trig.value(0)
    #start counting, the initial time of ultrasonic wave propagation in the air
    while Echo.value() == 0:
        Start = time.ticks_us()
    #The time of receiving the reflected ultrasonic wave
    while Echo.value() == 1:
        Stop = time.ticks_us()
    #The received time minus the initial time is the total time
    Time = time.ticks_diff(Stop,Start)
    #Calculate the distance according to the formula in meters.
    #Divide by 1000 to convert to centimeters.
    distance =  Time * soundVelocity //2 // 10000
    #Return the result of the calculation
    return distance

# Print the ultrasonic sensor value every 500 milliseconds
while True:    
    print('Distance: ', getDistance(), 'cm')
    time.sleep_ms(500)

Result:

After uploading the code, Shell prints the distance values and refreshes them per second. The distance can be viewed when you cover the sensor with your hand.

3.7.5 Code Explanation

  1. def getDistance():

    Create a function that drives the ultrasonic sensor to measure distance. Returns the measured result.

  2. print("Distance: ", getDistance(), "cm")

    Print the measured distance.

    Use commas to separate the content to be printed, and print the content inside the single quotation marks directly.