Leon Anavi
IT Tips && Tricks

Mobile & Embedded

Created: 07.10.2016 00:58 Last Modified: 08.10.2016 16:30 Views: 33702
Keywords: distance, HC-SR04, Python, Raspberry Pi

Detecting Distance on Raspberry Pi with HC-SR04


Recently I got the ultrasonic distance detection module called HC-SR04 from ICStation. It is a quite popular and fairly cheap module for Ardiuno or Raspberry Pi. People are often using it for do it yourself robots, smart cars and other toys.

Required Hardware

For this tutorial you will need:

  • Raspberry Pi (any model and version is suitable)
  • HC-SR04 distance detection module
  • Breadboard
  • 1kΩ Resistor
  • 2kΩ Resistor
  • Female to male and male to male jumper wires
  • microSD card with Raspbian GNU/Linux distribution


Connect HC-SR04 distance detection module to your Raspberry Pi as shown on the diagram below:

Wiring HC-SR04 distance detection module to Raspberry Pi

Source Code

Open a terminal on your Raspberry Pi or login remotely using SSH. If Python and Git are not install type the commands below to install it:

sudo apt-get update
sudo apt-get install -y git 
sudo apt-get install -y python-dev python-rpi.gpio

Type the following commands to get the source code and execute a Python script that displays the distance:

git clone https://github.com/leon-anavi/rpi-examples.git
cd rpi-examples/HC-SR04/python/
python distance.py

The Python script will show distance on each second. Move object near the sensor and observe how to output data changes, for example:

Distance: 5.4 cm
Distance: 8.5 cm
Distance: 265.4 cm
Distance: 264.7 cm
Distance: 386.6 cm
Distance: 232.4 cm
Distance: 231.2 cm
Distance: 230.5 cm
Distance: 215.7 cm
Distance: 136.4 cm
Distance: 9.6 cm
Distance: 145.7 cm
Distance: 131.8 cm
Distance: 129.8 cm
Distance: 219.2 cm
Distance: 5.7 cm
Distance: 7.8 cm
Distance: 15.7 cm
Distance: 2773.4 cm

Press Ctrl + C to terminate the execution of the Python script.

  Home | About | Contact | Disclaimer | Sitemap 2009-2022 Leon Anavi. All rights reserved.