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 with the HC-SR04 ultrasonic sensor with an ESP32 in MicroPython

(Updated at 01/04/2023)


The HC-SR04 sensor is a device that can measure the distance to an obstacle using ultrasonic waves. It consists of three components: an ultrasonic transmitter, a receiver, and a chip to control them.


Please check that your module is an HC-SR04 . It is usually colored blue and needs 5V to work. Please distinguish it from the RCWL-1606 , which is generally green and needs 3.3V. Although they work differently, they are both driven in the same way.

Getting started with the HC-SR04 module

Operation of an ultrasonic sensor

fonctionnement physique ultrason

If you’d like to understand how the HC-SR04 module works, you can check out this article which explains the module’s physical function in detail.

Technical specifications of the HC-SR04 module

  • The module requires a 5V power supply.

  • Consumption: The sensor requires 20mA of power to function correctly.

  • Range: The module can measure distances between 3cm to 4m. However, I recommend using it for lengths between 10cm and 2.5m for the best results.


    For accurate readings, the obstacle’s surface must be even.

  • Measurement angle: < 15°

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

HC-SR04 Sensor Wiring on ESP32

In addition to the power pins, we can use two pins to control the module. It is more convenient to use both pins, but if you don’t have more pins available, you can use just one.

Pin Wiring

HC SR04 Module











For this example, pins 5 and 18 have been chosen for the output TRIG and the input ECHO , respectively. However, you can use other compatible pins of the ESP32 .

Circuit with the HC-SR04 module and an ESP32


Circuit électrique à réaliser avec le HC-SR04


Circuit fait sur breadboard

How power the module: 5V or 3.3V?

The HC-SR04 module is not the best choice for ESP32 boards because it operates with 5V (with 5V logic levels), whereas ESP32 works in 3.3V. It must be powered with 5V, and either level shifters or voltage dividers must be added to the ECHO pin. This will allow the ESP32 GPIO18 pin to receive 3.3V instead of the original 5V, making the circuit a little more complex.


The ESP32 pins can support a voltage of 5V for temporary use. However, using this voltage for long-term use is not recommended as it can damage the pins and cause them to stop working. For this reason, this tutorial has not included any instructions on how to use 5V for long-term use.


Many people have reported success in powering the module with 3.3V and obtaining accurate readings by increasing the duration of the pulse sent. However, I could not make the ones I had work with 3.3V.

If you’re a beginner and use many boards that operate on 3.3V (e.g., ESP8266, ESP32, Raspberry Pi Pico), I recommend using a model specifically designed for this voltage, such as the RCWL-1601 .

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

The ESP32 can easily calculate the distance from an obstacle without needing external libraries. When the ESP32 sends an impulse on the TRIG , the module sends a pulse to the ECHO , which is proportional to the distance from the obstacle.

It is enough to implement the triggering of measurement, retrieve the value and apply the following formula (the obtaining of this formula is detailed in the article on the operation of an ultrasonic sensor)

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

This is what the code below does:

from machine import Pin, time_pulse_us
import time

SOUND_SPEED=340 # Vitesse du son dans l'air

trig_pin = Pin(5, Pin.OUT)
echo_pin = Pin(18, Pin.IN)

while True:
    # Prepare le signal
    # Créer une impulsion de 10 µs

    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")

The program produces a 10µs pulse sent to the GPIO5 of the ESP32 microcontroller.

The function time_pulse_us() pauses the program until it receives a response pulse from the HC-SR04 connected to pin 18 . After that, the code calculates the distance from the duration of the ultrasound wave. The program then shows the distance between the module and an object (like my hand in this example 🙂 ) in the serial monitor.

distance ultrason hcsr04 µpython


If you obtain negative values close to 0 (Distance: -0.017 cm ), the ultrasonic module didn’t receive the wave it sent out. This could be because the time_pulse_us() function timed out. To get accurate measurements, the surface of the obstacle should be flat.

MicroPython libraries for the HC-SR04

When you need to control multiple ultrasonic sensors and keep the calculations hidden, a library can be a great help.

Basic library, with blocking measures

Here is a short library code to drive the ultrasonic sensor. You can either save it in a separate file on the ESP32 (with the name ) or include it directly in your main script:

import machine, time
from machine import Pin

class HCSR04:
            # © 2021 Roberto Sánchez Apache License 2.0

            # echo_timeout_us is based in chip range limit (400cm)





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

Subscribe for only 5$/month

Already subscribed? Sign in