Electronic sensors are widely used in the field of robotics and in the new trend of the Internet of things to detect temperatures, humidity or sounds, among other elements that can provide information about the environment.
One of the most ingenious is the HC-SRO4 ultrasonic sensor, made up of a speaker and microphone. This sensor transmits an ultrasonic wave from the speaker that bounces off surrounding objects and is captured by the microphone, which is used to measure the distance between them and prevent collisions.
Next, we will see how to build a circuit to measure distances with an ultrasonic sensor and a Raspberry Pi 4. We will also provide you with the respective code.
1 x HC-SR04 ultrasonic sensor, 1 breadboard, 1 1KΩ resistor, 1 2kΩ resistor
The HC-SR04 ultrasonic sensor has 4 pins: Vcc, used to power the device; Trig, activates the sending of a sound pulse; Echo, sends a pulse to the Raspberry when it catches the bounce of a pulse of sound; and Gnd.
We will connect each of these pins with those of the Raspberry using the breadboard and female/male, male/male cables.
To get started, place the ultrasonic sensor on the breadboard (see image). Then connect the Vcc pin to the 5 volt pin on the Raspberry. Next, connect the Trig pin to one of the GPIO pins (eg GPIO 25). And the Gnd pin to the GND pin.
The Echo pin must also be connected to one of the GPIO pins but not directly, but through a voltage divider. This is because the sensor works at 5 volts while the Raspberry pins work at 3.3 v.
How to build a voltage divider
A voltage divider is an electrical circuit whose purpose is to obtain an output voltage lower than the input. Its construction is very simple and only requires the use of resistors.
The value of the resistors is obtained by applying Ohm’s law to both resistors and taking into account that the current intensity is the same in the circuit.
According to Kirchhoff’s law:
Vin = V1 + Vout===> V1= Vin – Vout
Also: I1= I2 ===> (Vin – Vout)/Vout = R1/R2
In our case: input voltage (Echo pin) = 5 v; output voltage (Vout)= 3.3v (GPIO pin)
After making the respective substitutions:
R1/R2 = 0.51
Therefore, we can use any two resistors as long as they keep that ratio. For example, one of 1 kΩ and one of 2 kΩ.
How to connect the Echo pin to the GPIO pin using a voltage divider
Connect one end of the 1 kΩ resistor to the Echo pin, and the other end to a 2 kΩ resistor. Connect the other end of the 2 kΩ resistor to the Raspberry Pi’s GND.
Python code to measure distances with an ultrasonic sensor and Raspberry Pi
from gpiozero import DistanceSensor from time import sleep sensor=DistanceSensor(23,25) while True: print('The distance to the object is: ', sensor.distance*100, 'cm') sleep(1)
To run the code, click on the Raspberry menu and select Programming > mu. Then copy and paste the code. Click Save and save the file with a .py extension to your hard drive. Finally, click on Run.