2.3 Ultrasonic Sensor
The ultrasonic sensor measures the distance to an object using sound waves. It is a non-contact sensor and outputs the distance in centimeters or inches.
Example Applications:
- Obstacle detection for autonomous robots
- Liquid level monitoring in tanks
- Proximity alert systems
2.3.1 Example Code for the Ultrasonic Sensor
- Start by connecting the ultrasonic sensor to one of the available dual-pin ports using the provided Type-C cable.
- The ultrasonic sensor requires both a TRIG and ECHO data line. Choose a port with two pins such as (P14/P13) or (P1/P0).
- Drag a
ScreenDisplay
block to your workspace first. - Next, drag the
read ultrasonic sensor unit
function from the code blocks section and insert it inside theScreenDisplay
block. - From the dropdown menus in the
read ultrasonic sensor unit
block:- Set TRIG to
P1
and ECHO toP0
if the sensor is connected to the P1/P0 port. - Alternatively, set TRIG to
P14
and ECHO toP13
for the P14/P13 configuration.
- Set TRIG to
- This setup will:
- Continuously measure the distance to an object in front of the sensor
- Display the real-time distance value on the screen

Figure 2.3.1a: Ultrasonic sensor reading displayed using block-based code