Raspberry Pi Ultrasonic Distance Sensor Project

In the first project of the Raspberry Pi project series, we will be constructing a detector that alerts us when the HC-SR04 ultrasonic sensor senses an object that exceeds a certain distance threshold. Since this is the first project of the series, not only will the Raspberry Pi be introduced, but also the software, components and pinout that will be involved. This is considered to be a project suitable for beginners but can certainly be expanded upon to suit other, much larger applications for more advanced electronic enthusiasts.

Raspberry Pi background

Table of Contents

HC-SR04 Ultrasonic Sensor Project Principle

The Raspberry Pi is the main microcontroller that will be used to program and receive data from the HC-SR04 sensor. Since it is a fully-fledged computer that operates on the Linux operating system, it is much more capable than an Arduino but for this series of projects, we will be exploring its microcontroller capabilities. Regarding the programming language that will be used, Python 3 is the main language that enables us to interface various sensors & modules with the Raspberry Pi due to its large variety of libraries & resources. By the way, although the Raspberry Pi 3 Model B is featured in all of these projects, any Raspberry Pi should be compatible to use for these projects (e.g. Raspberry Pi 2, 4, Zero, etc) as long as you have a basic programming environment (software) that is compatible with Python. For this example, I recommend mu or Thonny (used in this example) since they are beginner-friendly but even nano within the Raspberry Pi terminal works. Any operating software that can run a Python IDE (integrated development environment) should work fine but for the context of these projects, Raspbian will be used.

Regarding how this project works, a message in your Python IDE will be displayed when the ultrasonic sensor detects an object that exceeds its distance threshold, which can be set according to your preference. To start with, the HC-SR04 ultrasonic sensor is capable of measuring distances as it relies on two ultrasonic transducers (one transmitter & one receiver). The transmitter will emit 40 KHz ultrasonic pulses that will bounce off objects in its path and the ultrasonic waves that are reflected will be detected by the receiver. Based on the time that it takes for the transmitter to emit those ultrasonic waves and the receiver to detect the incoming waves from the object, distance can then be calculated. This makes the HC-SR04 ultrasonic sensor an excellent, affordable distance sensor to be used for an accurate distance range of up to 2 meters. If we take a look at the pinout of the HC-SR04 sensor, it is based on a 4-pin configuration that includes a VCC, Trigger, Echo and GND pin. The Trigger and Echo pin work together during the function of the sensor as the Trigger pin is primarily used to initiate the transmission of ultrasonic pulses by setting it HIGH. When the ultrasonic pulse is transmitted, the Echo pin is automatically set and remains HIGH until it receives the bounced-back pulse that sets it back to LOW. This mechanism is essentially the basis of how the HC-SR04 ultrasonic sensor works.

Required Components

For this project, these are the components that are required:

  • Raspberry Pi (any model should work)
  • Breadboard
  • Male-Male Jumper Wire (1)
  • Male-Female Jumper Wires (4)
  • HC-SR04 Ultrasonic Sensor
  • 1KΩ resistors (2)

Wiring

The reason why the Echo pin from the HC-SR04 sensor is not directly connected to a GPIO pin on the Raspberry Pi is due to the fact that the voltage needs to be stepped down from 5v to 3.3v before inputting to the Pi. This means that a voltage divider is required in place and in this case, two 1KΩ resistors are connected in series to act as the voltage divider that will step the voltage down to a safe level, although it is slightly below 3.3v, the maximum permissible voltage. If you are brand new to the Raspberry Pi, connecting wires to the Pi may be a bit daunting at first due to none of the 40 pins having any labels to indicate what pin it may be. This means that it is recommended that you always follow a pinout guide to identify pins and to additionally double-check your wiring before powering up the Pi to avoid any shorts. Other than that, the wiring for this project is fairly simple as aside from the main sensor, not a lot of extra components are needed. In terms of the HC-SR04 ultrasonic sensor, it runs on a simple 4-pin configuration as explained in the introductory section. A circuit diagram of the wiring is also featured below.

  • HC-SR04 Ultrasonic Sensor: Connect VCC to 5v (Pin 02) on your Raspberry Pi, the trigger (Trig) pin to GPIO04 (Pin 07) and GND to GND (Pin 06).
  • Voltage divider (on a breadboard): Connect a 1KΩ resistor from the Echo pin on the HC-SR04 sensor to a pin on the other half of the breadboard. Then, connect a jumper wire from that same row to GPIO17 (Pin 11) on your Pi. Also, connect another 1KΩ resistor from that row to a separate row to form the voltage divider and connect the end of that resistor to the GND pin of your HC-SR04 sensor.
Connect Ultrasonic Sensor to Raspberry Pi
Now, you are ready to get started with running the code and getting this project up and running!

Project Code

				
					from gpiozero import DistanceSensor
ultrasonic = DistanceSensor(echo = 17, trigger = 4, threshold_distance = 0.1)
def detect():
    print ("Detected!")
ultrasonic.when_in_range = detect
				
			

About the code

This code starts by importing the GPIO Zero library, a Raspberry Pi Python library that is meant to help users interface GPIO devices with the Pi. Next, we declare a specific hardware component that is used in this project: a Distance Sensor, the HC-SR04 ultrasonic sensor.

Next, we place the DistanceSensor function into a variable called ultrasonic. This function has three arguments that needed to be specified: the echo, trigger and threshold_distance arguments. The echo and trigger arguments are both set to the respective GPIO pins on the Raspberry Pi that those pins are connected to from the HC-SR04 sensor, GPIO17 (Echo) and GPIO04 (Trigger). Next, a distance threshold (in meters) is set which determines the minimum distance that an object needs to be detected by the sensor, in order to trigger another function. In this case, it is for a message to be printed to the IDE. In the above example code, the threshold is set to 0.1 meters but it can certainly be changed to a distance of up to 2 meters.

Next, we set up a function called ‘detect’ that will run when an object is detected within the threshold distance of the ultrasonic sensor. This function is set to print out the word “Detected!”. The last line of the code states that when the ultrasonic sensor detects an object within the threshold range, the function ‘detect’ will be triggered, printing out a message to the IDE. That wraps up this short, yet highly functional piece of code for this project.

Next steps

As the first project in the Raspberry Pi project series, TechSparks hope that you have been introduced to the GPIO capabilities of the Raspberry Pi and how it can interface with a GPIO device like the HC-SR04 ultrasonic sensor. If you are brand new to electronics, we also hope that you have learned some basic skills such as connecting hardware to the Pi’s GPIO pins, using a Python IDE and/or familiarizing yourself with how the Python GPIO Zero library can works with an ultrasonic sensor. Using IDEs such as mu or Thonny is a great way to introduce newbies to the electronics hobby and the Raspberry Pi as it features a simple interface that can be utilized for a wide variety of projects. In regards to the HC-SR04 ultrasonic sensor, it is commonly used for robotics projects, automobile devices (e.g. reverse sensors), home automation systems, etc and although this project only features one of its primary functions, it can undoubtedly be expanded upon. Moving forward to constructing other projects, some of the tips that you should keep in mind when working with the Raspberry Pi is to always check the wiring and pinout of that 40-pin header before anything is connected to power. Also, getting a good grip on Python is a valuable skill that we recommend you pick up and learn as you progress throughout your electronics journey.

Scroll to Top