The HC-SR04 Ultrasonic Distance Sensor is a great way to measure distance using your Raspberry Pi. In this guide, I’ll show you how to wire the sensor, set up a voltage divider, and write a Python script to calculate distance readings.
The Raspberry Pi’s GPIO pins work at 3.3V logic, but the HC-SR04’s ECHO pin outputs 5V. To safely connect it, we need a voltage divider that reduces 5V to 3.3V.For this, we’ll use:
- 1kΩ resistor (R1)
- 2kΩ resistor (R2)
This creates the correct voltage drop, protecting your Pi.
Wiring the HC-SR04 to Raspberry Pi
Here’s the wiring setup:
- VCC → Pin 2 (5V)
- Trig → Pin 7 (GPIO 4)
- Echo → R1 (1kΩ resistor)
- R2 (2kΩ resistor) → from R1 to Ground
- Wire between R1 & R2 → Pin 11 (GPIO 17)
- GND → Pin 6 (Ground)
Steps to Build the Circuit:
- Connect Pin 6 (GND) to the breadboard ground rail
- Connect Pin 2 (5V) to the VCC of the HC-SR04
- Connect Pin 7 to the Trig pin
- Place a 1kΩ resistor from Echo pin to breadboard
- Connect a 2kΩ resistor from the same row to ground rail
- Connect a jumper from between R1 & R2 to Pin 11 on the Pi
Writing the Python Script
We’ll now create a Python script to read distance values.
Step 1: Create a folder and file
Step 2: Add the following code
Step 3: Save and exit
Press CTRL+X, then Y, and hit ENTER.
Running the Code
Run the script with:
If everything is wired correctly, you’ll see something like:
Your reading will vary depending on the object in front of the sensor.
How It Works
- The Trig pin sends a short ultrasonic pulse.
- The Echo pin measures the time it takes for the pulse to bounce back.
- Using the speed of sound (343 m/s), we calculate distance with:
(The divide by 2 accounts for the pulse traveling to the object and back.)
You’ve now successfully:
- Wired the HC-SR04 to your Raspberry Pi
- Built a safe voltage divider for the Echo pin
- Written a Python script to measure distance
This setup is the foundation for robotics, obstacle detection, and smart automation projects with Raspberry Pi.
0 Comments