🐱 Tutorial 29 - Ultrasonic Sensor

The Ultrasonic Sensor Module is a non-contact distance measurement module that uses ultrasonic waves to detect the distance between the module and an object. It is commonly used in robotics, automation, and security systems for obstacle avoidance, distance measurement, and object detection.

The Ultrasonic Sensor Module works by emitting a high-frequency sound wave and measuring the time it takes for the sound wave to bounce back after hitting an object. The module contains a transducer that emits the sound wave and a receiver that detects the reflected wave.

The Ultrasonic Sensor Module is easy to use and can be integrated into electronic projects using a variety of programming languages, including C, C++, and Python. It typically operates at a frequency of 40 kHz and has a detection range of up to several meters, depending on the model.

Overall, the Ultrasonic Sensor Module is a versatile and widely-used distance measurement module that provides a simple and effective way to measure distances without physical contact. Its ease of use and compatibility with a wide range of devices make it a popular choice for hobbyists and professionals alike.

Components Needed

Raspberry Pi Pico W1
Micro USB Cable1
Ultrasonic Sensor Module1

Fritzing Diagram


import machine
import time

TRIG = machine.Pin(17,machine.Pin.OUT)
ECHO = machine.Pin(16,machine.Pin.IN)

def distance():
    while not ECHO.value():
    time1 = time.ticks_us()
    while ECHO.value():
    time2 = time.ticks_us()
    during = time.ticks_diff(time2,time1)
    return during * 340 / 2 / 10000

while True:
    dis = distance()
    print ('Distance: %.2f' % dis)

Code Explanation