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.3 Code Blocks

j26

This block reads the distance value. You can modify its unit into cm (default) or inch.

3.7.4 Test Code

3.7.4.1 Build Code

There are two ways to upload the code: directly open the code file we provide; or manually build blocks.

Directly open the code file we provide:

  1. Click and choose Load from your computer

  1. We have already downloaded the codes on computer desktop, so open the file and choose 3-7-ultrasonic.sb3

Manually build blocks:

  1. In events, find j1 block.

  2. In serial, find j12 block and set baud rate to 9600, and put it under j1.

  3. In control, put j2 under 6-4-4-1-1

6-2

  1. In serial, put j13 in the block j2 and set the printing content to “Distance:” in no-warp mode.

6-7

  1. In serial, put j13 under the block image-20240628092544675

  2. In 6-7, put j26 into the printing content of j13.

  3. At last add a delay of 0.5S for better observing results.

Complete Test Code

6-7

3.7.4.2 Test Result

After uploading code, the serial monitor prints the distance values and refreshes them per second.

6-7