Distance Detection Module
Introduction (How it Works)
The ultrasonic sensor HC-SR04 is a quite popular and fairly cheap module for Raspberry Pi. It works by emitting ultrasound waves at 40,000 Hz which travels through the air and if there is an object or obstacle on its path it will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance. It can be used in robots, smart cars, toys and many more…
Required Hardware
For this module you will need:
- Raspberry Pi (any model)
- HC-SR04 ultrasonic sensor
- Breadboard
- 1kΩ Resistor
- 2kΩ Resistor
- Female to male and male to male jumper wires.
- microSD card with Raspbian installed.
Wiring
Connect HC-SR04 distance detection module to your Raspberry Pi as shown in the diagram below:

Code
On your Raspberry Pi, open a terminal window. Install python by the following commands:
sudo apt-get update
sudo apt-get install -y python-dev python-rpi.gpio
Download and save this file to your desktop
With the following commands you can execute the Python script that displays the distance:
cd Desktop
python sonic.py
The script will show distance every second. Press Ctrl + C to terminate the execution of the Python script.