Project

โ— Beginner ยท HC-SR04 Ultrasonic Distance Sensor

Measuring Distance with HC-SR04 on Raspberry Pi Pico

Overview

Learn how to use the HC-SR04 ultrasonic sensor to measure distance in centimeters using a Raspberry Pi Pico. This project is useful for obstacle detection, smart parking, and distance-based alarms.

Instructions

Step by step

1. Connect the HC-SR04 VCC pin to 5V. 2. Connect the HC-SR04 GND pin to GND. 3. Connect the Trig pin to GP3. 4. Connect the Echo pin to GP2. 5. If using real hardware, use a voltage divider on Echo because the Pico uses 3.3V logic. 6. Run the code and open the Serial/console output. 7. Change the object distance and check if the printed distance changes in centimeters.

Code

Source code

code
from machine import Pin, time_pulse_us
import utime

trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

while True:
    trig.low()
    utime.sleep_us(2)

    trig.high()
    utime.sleep_us(10)
    trig.low()

    duration = time_pulse_us(echo, 1)
    distance = (duration * 0.0343) / 2

    print("Distance:", distance, "cm")
    utime.sleep(1)

Related

More projects with this sensor