Ultrasonic Distance Sensor Project 🦇

If you've seen Batman Begins, you'll remember the scene where Batman uses a device that emits ultrasonic signals. While we won't be building a bat-summoning beacon today, we will work with similar ultrasonic technology.

What is Ultrasonic?

Ultrasonic waves are sound waves with frequencies above 20,000 Hz, beyond what human ears can detect. Bats use ultrasonic waves to fly in the dark and avoid obstacles. Dolphins use them to communicate and sense objects underwater.

The HC-SR04+ Sensor

The HC-SR04+ is a simple and low-cost ultrasonic distance sensor that can measure distances from about 2 cm up to 400 cm. It works by sending out a short burst of ultrasonic sound and listening for the echo.

Important: HC-SR04 vs HC-SR04+

The HC-SR04 normally operates at 5V, which can damage the Raspberry Pi Pico. If possible, purchase the HC-SR04+ version, which works with both 3.3V and 5V. If you have the standard HC-SR04, you'll need a voltage divider on the Echo pin.

How It Works

Ultrasonic sensors emit sound waves at 40kHz that travel through air and bounce back when they hit an object. By measuring the time it takes for the echo to return, we can calculate distance using this formula:

Distance = (Time × Speed of Sound) / 2

The speed of sound is approximately 0.0343 cm/µs at normal air pressure and 20°C temperature.

Hardware Requirements

Wiring the HC-SR04

Pico 2 PinHC-SR04 PinNotes
VBUS (Pin 40) or 3.3VVCC5V for HC-SR04, 3.3V for HC-SR04+
GPIO 17TrigTrigger pin
GPIO 16EchoUse voltage divider if using 5V HC-SR04
GNDGNDCommon ground

Project: LED Proximity Detector

We'll build a proximity detector that gradually brightens an LED as objects get closer. When the sensor detects something within 30 cm, the LED glows brighter using PWM. The closer the object, the brighter the LED.

Key Concepts Used

  • GPIO input and output configuration
  • PWM for LED brightness control
  • Microsecond timing for ultrasonic pulse measurement
  • Distance calculation using speed of sound
  • Timeout handling for reliable sensor reading

Complete code examples for both Embassy and rp-hal are available in the project repositories. The examples include proper error handling, timeout management, and LED brightness mapping based on distance.