Raspberry Pi Pico - Ultrasonic Sensor

This guide shows you how to use the ultrasonic sensor and Raspberry Pi Pico to find out how far away an object is. We will learn about:

Raspberry Pi Pico ultrasonic sensor

Hardware Preparation

1×Raspberry Pi Pico W
1×Raspberry Pi Pico (Alternatively)
1×Micro USB Cable
1×Ultrasonic Sensor
1×Jumper Wires
1×(Optional) Screw Terminal Expansion Board for Raspberry Pi Pico

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Ultrasonic Sensor

The HC-SR04 ultrasonic sensor calculates how far objects are by using sound waves. It emits a sound wave that cannot be heard by humans and waits to hear the echo that comes back after bouncing off an object. By timing how long it takes for the echo to return, the sensor figures out the distance to the object.

Pinout

The HC-SR04 ultrasonic sensor has four pins.

  • VCC pin: Connect this pin to VCC (5 volts).
  • GND pin: Connect this pin to GND (0 volts).
  • TRIG pin: Connect this to the Raspberry Pi Pico to send control signals.
  • ECHO pin: This sends signals back to the Raspberry Pi Pico, which measures these signals to find out distance.
Ultrasonic Sensor Pinout
image source: diyables.io

Wiring Diagram

The wiring diagram between Raspberry Pi and Pico Ultrasonic Sensor

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Pico Code

Before using Ultrasonic Sensor libary, we will try to program Raspberry Pi Pico without using library to understand how it works.

from machine import Pin, Timer import time # Define the pins for the trigger and echo trig = Pin(1, Pin.OUT) # The Raspberry Pi Pico pin (GP1) connected to TRIG pin of the ultrasonic sensor echo = Pin(0, Pin.IN) # The Raspberry Pi Pico pin (GP0) connected to ECHO pin of the ultrasonic sensor def read_distance(): # Ensure the trigger pin is low for a clean pulse trig.value(0) time.sleep_us(2) # Send a 10 microsecond pulse to start the measurement trig.value(1) time.sleep_us(10) trig.value(0) # Measure the duration of the echo pulse while echo.value() == 0: signal_off = time.ticks_us() while echo.value() == 1: signal_on = time.ticks_us() # Calculate the duration of the echo pulse time_passed = signal_on - signal_off # Calculate the distance in centimeters distance = (time_passed * 0.0343) / 2 return distance # Check the sensor every 1 seconds while True: distance = read_distance() print('Distance:', distance, 'cm') time.sleep(1)

Detailed Instructions

Please follow these instructions step by step:

  • Ensure that Thonny IDE is installed on your computer.
  • Ensure that MicroPython firmware is installed on your Raspberry Pi Pico.
  • If this is your first time using a Raspberry Pico, refer to the Raspberry Pi Pico - Getting Started tutorial for detailed instructions.
  • Wire the Raspberry Pi Pico to the ultrasonic sensor according to the provided diagram.
  • Connect the Raspberry Pi Pico to your computer using a USB cable.
  • Launch the Thonny IDE on your computer.
  • On Thonny IDE, select MicroPython (Raspberry Pi Pico) Interpreter by navigating to Tools Options.
  • In the Interpreter tab, select MicroPython (Raspberry Pi Pico) from the drop-down menu.
  • Ensure the correct port is selected. Thonny IDE should automatically detect the port, but you may need to select it manually (e.g., COM3 on Windows or /dev/ttyACM0 on Linux).
  • Copy the above code and paste it to the Thonny IDE's editor.
  • Save the script to your Raspberry Pi Pico by:
    • Click the Save button, or use Ctrl+S keys.
    • In the save dialog, you will see two sections: This computer and Raspberry Pi Pico. Select Raspberry Pi Pico
    • Save the file as main.py
  • Click the green Run button (or press F5) to run the script. The script will execute.
  • Move your hand in front of the ultrasonic sensor.
  • Check out the message in the Shell at the bottom of Thonny.
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot Distance: 29.4 cm Distance: 27.6 cm Distance: 26.9 cm Distance: 17.4 cm Distance: 16.9 cm Distance: 14.3 cm Distance: 15.6 cm Distance: 13.1 cm
MicroPython (Raspberry Pi Pico) • Board CDC @ COM29 ≡

If you name your script main.py and save it to the root directory of the Raspberry Pi Pico, it will automatically run each time the Pico is powered on or reset. This is useful for standalone applications that need to start running immediately upon power-up. If you name your script another name other than main.py, you will need to manually run it from Thonnys's Shell.

Code Explanation

The explanation can be found in the comments of the above Raspberry Pi Pico code.

How to Filter Noise from Distance Measurements of Ultrasonic Sensor

The data from the ultrasonic sensor has extra, unnecessary signals, which we call noise. Sometimes this noise can cause the sensor to work wrongly. We can remove this noise by using the following method:

  • Measure multiple times and store these measurements in a list.
  • Arrange the list in order from the smallest to the largest value.
  • Clean the data by removing noise:
    • Ignore the smallest values because they are considered noise.
    • Ignore the largest values because they are also considered noise.
    • Find the average of the remaining values in the middle.

    The example code below makes 20 measurements.

    • Leave out the five smallest and the five largest samples because they are considered noise. Calculate the average of the ten middle samples, ranging from the 5th to the 14th.

    The below MicroPython code implements the above algorithm:

    """ This Raspberry Pi Pico MicroPython code was developed by newbiely.com This Raspberry Pi Pico code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pico/raspberry-pi-pico-ultrasonic-sensor """ from machine import Pin, Timer import time # Define the pins for the trigger and echo trig = Pin(1, Pin.OUT) echo = Pin(0, Pin.IN) # Define an array to store measurements filter_array = [] def read_distance(): # Ensure the trigger pin is low for a clean pulse trig.value(0) time.sleep_us(2) # Send a 10 microsecond pulse to start the measurement trig.value(1) time.sleep_us(10) trig.value(0) # Measure the duration of the echo pulse while echo.value() == 0: signal_off = time.ticks_us() while echo.value() == 1: signal_on = time.ticks_us() # Calculate the duration of the echo pulse time_passed = signal_on - signal_off # Calculate the distance in centimeters distance = (time_passed * 0.0343) / 2 return distance def take_measurements(): global filter_array filter_array = [read_distance() for _ in range(20)] time.sleep_ms(30) # delay to avoid ultrasonic interference def filter_measurements(): global filter_array filter_array.sort() # Consider only the middle 10 samples middle_samples = filter_array[5:15] return sum(middle_samples) / len(middle_samples) while True: take_measurements() filtered_distance = filter_measurements() if filtered_distance > 140: print('No object detected within the set distance') else: # Print the distance formatted to two decimal places using format() print('Filtered distance: {:.2f} cm'.format(filtered_distance)) time.sleep(1)
    • Copy the above code and paste it to the main.py on the Thonny IDE's editor.
    • Save the script to your Raspberry Pi Pico.
    • Click the green Run button (or press F5) to run the script. The script will execute.
    • Move your hand in front of the ultrasonic sensor.
    • Check out the message in the Shell at the bottom of Thonny.
    Shell x
    >>> %Run -c $EDITOR_CONTENT
    MPY: soft reboot MPY: soft reboot No object detected within the set distance No object detected within the set distance No object detected within the set distance Filtered distance: 5.46 cm Filtered distance: 9.21 cm Filtered distance: 10.12 cm Filtered distance: 12.33 cm Filtered distance: 9.89 cm Filtered distance: 6.56 cm No object detected within the set distance No object detected within the set distance No object detected within the set distance No object detected within the set distance No object detected within the set distance
    MicroPython (Raspberry Pi Pico) • Board CDC @ COM29 ≡

Raspberry Pi Pico - Ultrasonic Sensor Libary

The above looks complicated, but fortunately, DIYables has develop the library to make it easy for you. You can follow the below step to use the Ultrasonic Sensor library:

  • On Thonny IDE, Navigate to the Tools Manage packages on the Thonny IDE.
  • Search “DIYables-MicroPython-Ultrasonic-Sensor”, then find the Ultrasonic Sensor library created by DIYables.
  • Click on DIYables-MicroPython-Ultrasonic-Sensor, then click Install button to install Ultrasonic Sensor library.
Raspberry Pi Pico Ultrasonic Sensor library
  • Copy the below code and paste it to the Thonny IDE's editor.
""" This Raspberry Pi Pico MicroPython code was developed by newbiely.com This Raspberry Pi Pico code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pico/raspberry-pi-pico-ultrasonic-sensor """ # example_usage.py from DIYables_MicroPython_Ultrasonic_Sensor import UltrasonicSensor import time sensor = UltrasonicSensor(trig_pin=1, echo_pin=0) sensor.set_detection_threshold(140) # Set detection threshold to 140 cm sensor.enable_filter(num_samples=20) # Enable filtering and set number of samples to 20 while True: sensor.loop() # Perform measurement cycle distance = sensor.get_distance() if not distance: print('No object detected within the set distance') else: # Print the distance formatted to two decimal places using format() print('Filtered distance: {:.2f} cm'.format(distance)) time.sleep(1) # Reduced sleep time to enhance measurement responsiveness
  • Save the script to main.py on your Raspberry Pi Pico
  • Click the green Run button (or press F5) to run the script. The script will execute.
  • Move your hand in front of the ultrasonic sensor.
  • Check out the message in the Shell at the bottom of Thonny.

Video Tutorial

Ultrasonic Sensor Applications

  • Preventing Crashes
  • Checking if Full
  • Checking Height
  • Sensing Nearness

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!