Using a Raspberry Pi distance sensor (ultrasonic sensor HC-SR04)

11. November 2015
36 Comments

For many (outdoor) projects a distance measurement is necessary or advantageous. These small modules are available starting at 1-2 bucks and can measure the distance up to 4-5 meters by ultrasound and are suprisingly accurate. This tutorial shows the connection and control.

 

Hardware

  • HC-SR04 Module (US / UK)
  • Resistors: 330Ω and 470Ω (US / UK)
  • Jumper wire (US / UK)

Wiring

There are four pins on the ultrasound module that are connected to the Raspberry:

  • VCC to Pin 2 (VCC)
  • GND to Pin 6 (GND)
  • TRIG to Pin 12 (GPIO18)
  • connect the 330Ω resistor to ECHO.  On its end you connect it to Pin 18 (GPIO24) and through a 470Ω resistor you connect it also to Pin6 (GND).

We do this because the GPIO pins only tolerate maximal 3.3V. The connection to GND is to have a obvious signal on GPIO24. If no pulse is sent, the signal is 0 (through the connection with GND), else it is 1. If there would be no connection to GND, the input would be undefined if no signal is sent (randomly 0 or 1), so ambiguous.

Here is the structure as a circuit diagram:

ultraschall_Steckplatine
 

Script for controlling

First of all, the Python GPIO library should be installed

To use the module, we create a new script

sudo nano ultrasonic_distance.py

with the following content:

After that we run:

sudo python ultrasonic_distance.py

So every second, the distance will be measured until the script is cancelled by pressing CTRL + C.
That‘s it. You can use it many fields, but who still want to measure larger distances would have to rely on laser measuring devices, which, however, are much more expensive.

Leave a Comment

Your email address will not be published.