Cover image for Ultrasonic sensors

Ultrasonic sensors

Ultrasonic sensors use high-frequency sound waves to measure the distance between the sensor and an object.

Robot Tips How it works

10 January 2023 by Kevin McAleer | Share this article on

Ultrasonic sensors use high-frequency sound waves to measure the distance between the sensor and an object.

When the sensor emits a sound wave, it will bounce off the object it hits and return back to the sensor. The sensor measures the time it takes for the sound wave to travel in order to calculate the distance between the object and the sensor.

Ultrasonic sensors are commonly used for industrial automation and robotics, as well as for safety and security applications.

The most commonly used Ultrasonic sensor, also known as a range finder, is the HC-SR04.

Picture of an Ultrasonic sensor

MicroPython Code

A typical piece of code for measuring distance will look like this:

from machine import Pin, PWM
import utime

trigger = Pin(14, Pin.OUT)
echo = Pin(15, Pin.IN)

buzzer = PWM(Pin(16))

def measure_distance():
    """ Returns the distance in mm"""
    while echo.value() == 0:
        signaloff = utime.ticks_us()
    while echo.value() == 1:
        signalon = utime.ticks_us()
    timepassed = signalon - signaloff
    distance = (timepassed * 0.0343) / 2
    return distance

while True:
    distance = measure_distance()

Did you find this content useful?

If you found this high quality content useful please consider supporting my work, so I can continue to create more content for you.

I give away all my content for free: Weekly video content on YouTube, 3d Printable designs, Programs and Code, Reviews and Project write-ups, but 98% of visitors don't give back, they simply read/watch, download and go. If everyone who reads or watches my content, who likes it, helps fund it just a little, my future would be more secure for years to come. A price of a cup of coffee is all I ask.

There are a couple of ways you can support my work financially:

If you can't afford to provide any financial support, you can also help me grow my influence by doing the following:

Thank you again for your support and helping me grow my hobby into a business I can sustain.
- Kevin McAleer