Skip to content

uPesy ships directly only in France !

uPesy products available on Amazon for EU

Contents Menu Expand Light mode Dark mode Auto light/dark mode

Measuring distances in MicroPython with the HC-SR04 ultrasonic sensor with a Pi Pico

(Updated at 01/04/2023)

../_images/hcsr04-rpi-pico-upesy-rp2040-boards-preview.jpg

The HC-SR04 sensor is a device that uses ultrasonic waves to detect and measure distances. This sensor has three components on it: an ultrasonic transmitter, a receiver, and a chip to control them.

Tip

Are you sure you’re using an HC-SR04 module? It may look similar to other ultrasonic modules like the RCWL-1601 . However, they use different chips. The HC-SR04 module is usually blue and only works with 5V. The RCWL-1601 module (typically green) can work with either 3.3V or 5V. Although they look different, they’re usually controlled in the same way.

Getting started with the HC-SR04 module on the Pico

Operation of an ultrasonic sensor

fonctionnement physique ultrason

It will help if you read up on how the**HC-SR04** module operates. An excellent place to start is t:ref:his article, which provides a comprehensive look at the physical workings of the module. <1d9f34276d494507a0a3695354a1b38a>

Technical specifications of the HC-SR04 module

  • Power supply: This module needs a 5V power supply to function correctly.

  • Consumption: The sensor uses 20mA of power when in use.

  • Range: This module can measure a distance between 3cm and 4m. However, it is recommended to use it with a distance between 10cm and 2.5m for the best results.

  • Measurement angle: < 15°.

    Warning

    The obstacle’s surface must be smooth and even to obtain reliable measurements.

  • Ultrasonic frequency: 40 kHz (inaudible to the ear)

HC-SR04 Sensor Wiring on Raspberry Pi Pico

Two pins are needed to control a Raspberry Pi Pico module, though you can use only one if more pins are unavailable. Having two pins is preferable for convenience.

Pin Wiring

HC-SR04 Module

Raspberry Pi Pico

ECHO

GP14

TRIG

GP15

GND

GND

VCC

5V

Note

For this case, we have selected pins 14 and 15 from the Pico. However, you may also use other pins available on the board.

Circuit with the HC-SR04 module and the Pico

ultrason hcsr04 microptyhon rpi picot

Circuit on breadboard

ultrason hcsr04 microptyhon rp2040 devkit

Circuit on breadboard

What is the correct power supply for the module: 5V or 3.3V?

The HC-SR04 module is not ideal for Raspberry Pi Pico boards because the board operates on 3.3V while the module requires 5V (5V logic levels). To compensate for this, you must supply the module with a 5V power source and add either level shifters or voltage dividers to the ECHO pin. This allows the GP14 pin on the Raspberry Pi Pico to receive 3.3V instead of the original 5V. However, this makes the circuit a bit more complex. On the output pin, the HC-SR04 module can detect a logic level of 3.3V as a high level, so no further adaptation is required.

Tip

In practice, the pins of the Pico can be used with a voltage of 5V. But it is essential to remember that if this is for a long-term project, the pins may be at risk of damage. Due to this, this tutorial does not mention such precautions for the sake of simplicity.

If you work with boards operating at 3.3V, such as the ESP8266, ESP32 and Raspberry Pi Pico, I suggest using the**RCWL-1601** , a model designed to run at this voltage.

Easily measure a distance with the HC-SR04 module and a MicroPython script

You don’t need to use external libraries since the process is simple. When the RPi Pico sends a pulse to TRIG , the module sends a pulse to ECHO , and the duration of the pulse is proportional to the distance from the object.

To measure this distance, trigger the measurement, get the value and use the following formula.

\[d_{obstacle}(cm) = \frac{T_{ultrason}(µs)\times v_{son}(m/s)\times 10^{-4}}{2}\]

Note

To get the formula for using an ultrasonic sensor, check out this article that explains the:ref:` operation of the sensor in detail. <1d9f34276d494507a0a3695354a1b38a>`

from machine import Pin, time_pulse_us
import time

SOUND_SPEED=340 # Vitesse du son dans l'air
TRIG_PULSE_DURATION_US=10

trig_pin = Pin(15, Pin.OUT) # Broche GP15 de la Pico
echo_pin = Pin(14, Pin.IN)  # Broche GP14 de la Pico

while True:
    # Prepare le signal
    trig_pin.value(0)
    time.sleep_us(5)
    # Créer une impulsion de 10 µs
    trig_pin.value(1)
    time.sleep_us(TRIG_PULSE_DURATION_US)
    trig_pin.value(0)

    ultrason_duration = time_pulse_us(echo_pin, 1, 30000) # Renvoie le temps de propagation de l'onde (en µs)
    distance_cm = SOUND_SPEED * ultrason_duration / 20000

    print(f"Distance : {distance_cm} cm")
    time.sleep_ms(500)

The program will create a 10µs pulse directed to the GP15 of the Raspberry Pi Pico.

The function time_pulse_us() pauses the program until it receives an ultrasound response pulse from the HC-SR04 module connected to pin 14 . Then, it calculates the distance of the ultrasound wave by the pulse duration. The outcome of the calculation, which is the distance between the module and an obstacle, can be viewed in the serial monitor. To demonstrate, here I’m using my hand to test it out! 🤗

distance ultrason hcsr04 µpython pico

Note

If the results from the ultrasonic module show a value close to 0 (Distance: -0.017 cm ), the wave sent could not be received. This could be due to a timeout of the time_pulse_us() function. For accurate measurement, the obstacle should have a flat surface.

MicroPython libraries for the HC-SR04 module and the Pico

Using a library can be helpful when dealing with multiple ultrasonic sensors simultaneously.

Basic library, with blocking measures

This library code can control an ultrasonic sensor with a Pico. You have two options for using the code: save it as a separate file on the Pico (called hcsr04.py ) or directly include it in your main script.

distance ultrason hcsr04 µpython pico

We can see the scripts and Python libraries saved on the Pico via View → Files

This section is available to premium members only. You still have 92% to discover.

Subscribe for only 5$/month

Already subscribed? Sign in