Raspberry Pi & HC-SR04 Distance Sensor

by drselim in Circuits > Raspberry Pi

1521 Views, 1 Favorites, 0 Comments

Raspberry Pi & HC-SR04 Distance Sensor

Raspberry Pi GPIO Programming with Python - Part 5: Distance Sensor

Hi, in this instructable, we'll see how to use the HC-SR04 Ultrasonic Distance Sensor with the Raspberry Pi.

We'll use Python and gpiozero library.

Supplies

Raspberry Pi (I'm using Pi 4, older models should also be OK), female to male jumper cables, breadboard (a small one is sufficient), 2 resistors: 220 Ohm & 470 Ohm, or any other resistors around 1:2 ratio will be fine), gpiozero library installed in python.

Circuit Diagram

circuit_diag.png

The connections will be:

Sensor Vcc --> 5V pin on Raspberry Pi

Sensor GND --> GND pin on Raspberry Pi

Sensor Trigger --> Pin23 on Raspberry Pi

Sensor Echo --> Pin22 on Raspberry Pi (over the voltage divider as seen in picture!)

The reason we're using the voltage divider is that the Raspberry Pi pins are expecting a voltage level of 3.3 V however the sensor is sending the signal at 5 V level.

Code

code1.png
code2.png

In the first code, we're importing DistanceSensor from GPIO library and we set the connections to the pins 23 and 24, and in an infinite loop we're printing the distance in meters.

In the second code, we add a buzzer to pin 17 and create a kind of parking sensor effect, as the object comes nearer, the beep frequency of the buzzer increases.

If you like the content please subscribe to my YouTube channel for similar tutorials and projects.

https://www.youtube.com/c/drselim

Thank you.