Skip to main content

Build. Learn.
Innovate.

Measuring Distance with an Ultrasonic Sensor

Written By:

Published on:

Project Overview

This project introduces students to ultrasonic sensors and how to measure distance using sound waves. They will learn about timing and calculating distance based on the time it takes for a sound pulse to return.

Educational Goals

  • Understand the concept of using sound waves for distance measurement.
  • Learn how the HC-SR04 ultrasonic sensor works.
  • Practice using digital input and output pins for timing.
  • Perform calculations in MicroPython.

Detailed Parts List

  • ESP32 – 1
  • HC-SR04 Ultrasonic Module Distance Sensor – 1
  • Breadboard – 1
  • Jumper Wires – Male-to-Male

Circuit Diagram Description

Connect the VCC pin of the HC-SR04 to the 5V or 3.3V pin on the ESP32 (check the sensor’s voltage requirements, but 5V is common for the HC-SR04 and the ESP32’s 5V pin can often supply enough current). Connect the GND pin to GND on the ESP32. Connect the Trig pin of the HC-SR04 to a digital GPIO pin on the ESP32. Connect the Echo pin of the HC-SR04 to another digital GPIO pin on the ESP32. Note that the Echo pin outputs a 5V signal, while the ESP32 GPIOs are typically 3.3V tolerant. It is recommended to use a voltage divider circuit (two resistors) on the Echo pin to safely step down the voltage to 3.3V for the ESP32’s input.

Software Functionality

The MicroPython code will send a short pulse from the Trig pin to initiate a distance measurement. It will then measure the time it takes for the Echo pin to go high and back low, indicating the time the sound pulse traveled to an object and returned. Using the speed of sound, the code will calculate the distance and print it to the console.

Web Interface Features

A web interface could display the measured distance numerically and potentially update in real-time.

Implementation Steps

  • Set up the MicroPython environment on the ESP32.
  • Connect the ultrasonic sensor circuit on the breadboard, including the voltage divider for the Echo pin if necessary.
  • Write the MicroPython code to control the sensor and calculate distance.
  • Upload and run the code on the ESP32.
  • Observe the distance readings in the console and test with objects at different distances.

Extensions and Challenges

  • Implement error handling for out-of-range readings.
  • Use the distance sensor to detect obstacles.
  • Combine with motors to create a simple robot that avoids obstacles.
  • Display the distance on an OLED screen.

Troubleshooting Guide

  • Incorrect distance readings: Ensure the speed of sound value used in the calculation is accurate for the ambient temperature (though for basic projects, a standard value is usually sufficient). Verify the timing logic in the code is correct. Check for interference if multiple ultrasonic sensors are used nearby.
  • No readings: Confirm all connections are secure, especially the voltage divider on the Echo pin. Verify the correct GPIO pins are used and configured correctly in the code.

Project Code

# This script measures distance using the HC-SR04 and displays it on an OLED screen.
# Note: Assumes voltage divider on Echo pin if needed.

from machine import Pin, I2C # Import Pin and I2C
import time                   # Import time

# Import the SSD1306 OLED driver library.
try:
    import ssd1306
except ImportError:
    print("ssd1306.py library not found. Please upload it to your ESP32.")
    class MockSSD1306:
        def __init__(self, width, height, i2c):
            print(f"MockSSD1306 initialized ({width}x{height}).")
        def fill(self, color): pass
        def text(self, text, x, y, color): pass
        def show(self): print(f"OLED display content not shown (ssd1306 library missing): {text}")
    ssd1306 = type('ssd1306', (object,), {'SSD1306_I2C': MockSSD1306})()


# --- Ultrasonic Sensor Setup ---
# Define the GPIO pin numbers connected to the HC-SR04 sensor.
trigger_pin = 4
echo_pin = 5
trigger = Pin(trigger_pin, Pin.OUT)
echo = Pin(echo_pin, Pin.IN)
speed_of_sound_cm_per_us = 0.0343

def measure_distance():
    """
    Measures the distance using the HC-SR04 sensor.
    Returns the distance in centimeters, or -1 on error/timeout.
    """
    trigger.value(0)
    time.sleep_us(2)
    trigger.value(1)
    time.sleep_us(10)
    trigger.value(0)

    pulse_start = time.ticks_us()
    pulse_end = time.ticks_us()

    timeout_us = 20000 # Timeout after 20ms
    start_time = time.ticks_us()
    while echo.value() == 0:
        pulse_start = time.ticks_us()
        if time.ticks_diff(pulse_start, start_time) > timeout_us:
            return -1

    start_time = time.ticks_us()
    while echo.value() == 1:
        pulse_end = time.ticks_us()
        if time.ticks_diff(pulse_end, start_time) > timeout_us:
            return -1

    pulse_duration_us = time.ticks_diff(pulse_end, pulse_start)

    if pulse_duration_us > 0:
        distance_cm = (pulse_duration_us * speed_of_sound_cm_per_us) / 2
        return distance_cm
    else:
        return -1

# --- OLED Setup ---
i2c_sda = 21
i2c_scl = 22
oled_width = 128
oled_height = 32

i2c = I2C(0, sda=Pin(i2c_sda), scl=Pin(i2c_scl), freq=400000)
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

print("Starting ultrasonic distance measurement with OLED display...")

# Start an infinite loop to continuously measure and display the distance.
while True:
    # Get the distance measurement.
    distance = measure_distance()

    # --- Display on OLED ---
    oled.fill(0) # Clear display

    oled.text("Distance:", 0, 0, 1)

    if distance != -1:
        # Display the distance.
        oled.text("{:.1f} cm".format(distance), 0, 16, 1) # Display value with units
        print("Distance: {:.1f} cm".format(distance))
    else:
        # Display an error or out of range message.
        oled.text("Out of Range", 0, 16, 1)
        print("Distance: Out of Range or Error")


    # Update the OLED display.
    oled.show()

    # Wait for a short duration before taking the next measurement.
    time.sleep(0.5)

# This loop will run forever.

# Troubleshooting notes:
# - See troubleshooting notes from Project 2 and Project 3.
# - Ensure voltage divider is used on Echo pin if your HC-SR04 is 5V and ESP32 is 3.3V.

STEM Benefits

Science:

  • Sound Waves: Understanding how ultrasonic waves are used to detect objects and measure distance (echolocation principle).
  • Speed of Sound: Learning that sound travels at a specific speed, which is crucial for distance calculation.
  • Reflection: How sound waves bounce off surfaces.

Technology:

  • Sensors: Using an ultrasonic sensor for distance measurement.
  • Digital Input/Output: Using GPIO pins to send a trigger pulse and read the echo response.
  • Timing: Precisely measuring the time duration of the echo pulse.

Engineering:

  • Sensor Interfacing: Connecting and communicating with the ultrasonic sensor.
  • System Design: Integrating the sensor with the microcontroller for a specific task (measuring distance).
  • Troubleshooting: Addressing issues with inaccurate or inconsistent readings.

Mathematics:

  • Measurement: Taking distance measurements.
  • Calculations: Using the formula distance = speed × time (and dividing by two since the sound travels to the object and back).
  • Units and Conversions: Working with units of time, speed, and distance.

Projects
ShowCase

Real-World Projects
with Code & Hardware

Insights, Ideas
& How-Tos

Help, Support, and
Common Questions

What types of projects can I find on your website?

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.