Many applications require precise distance measurement. One of the ways you can measure it is by using an Ultrasonic Sensor. This device uses sound waves and the reflection of the sound wave (echo) to measure the distance. Similarly, a bat uses high-pitched sounds to map the obstacles around them. Most of the ultrasonic sensors can identify obstacles up to 5 meters. But unlike bats ultrasonic sensors calculate the distance between themselves and the points in front of them utilizing sound waves and basic measurements. Hence it’s primarily used in robotics to prevent the bot from walking or rolling into an obstacle. Ultrasonic sensor use a technique called ECHO.
The term “ECHO” refers to a sound wave that has been echoed. When sound bounces back after hitting a dead end, you’ll receive an ECHO. For more assistance, this video demonstrates how to mount and operate an ultrasonic sensor.
Ultrasonic Transmitter: One or two ultrasonic transmitters (speakers), a receiver, and a control circuit make up a simple ultrasonic sensor. The transmitters emit a high-frequency ultrasonic sound that bounces off solid objects in the region. Any ultrasonic noise is mirrored and picked up by the sensor’s receiver.
Ultrasonic Receiver: The control circuit processes the return signal to determine the time difference between the transmitted and received signals. This time, it will be used to measure the distance between the sensor and the reflected object using some clever arithmetic.
Table of Contents
Bill of materials
|Raspberry Pi Pico (Hardware)||The Raspberry Pi Pico is a microcontroller board similar to Arduino rather than a Linux device. The Raspberry Pi Pico’s main selling points are its $4 price tag. The latest RP2040 chip, offers plenty of power for embedded projects and allows people of any age or skill to learn coding and electronics.|
|The HC-SR04 is an ultrasonic range finder that generates 0V and 5V, which must be transformed to 0V and 3.3V for proper processing by the Raspberry Pi Pico.|
Pulling the ‘Trigger’ pin high for 10us initiates the calculation.
The HCSR04 module also generates ultrasonic sound vibrations, which provide an 8-cycle acoustic blast at the speed of sound.
|Jumper wires (Hardware)||Jumper wires are convenient for wiring with connection pins on both ends without the use of solder. It is used for breadboards and other prototyping equipment and are allowed for simple circuit changes. Jumper wires comes in a variety of colors. Colors are used to distinguish between various types of links, such as land and electricity.|
There are 3 types of jumper wires as follows: –
Male to male
Male to female
Female to female
The distinction between them is in the wire’s endpoint. Male ends have a protruding pin that can be plugged, while female ends are used to plug into things. Male-to-Male jumper wires are the most popular and the ones you will need. A male-to-male wire is needed when connecting two ports on a breadboard.
|A breadboard is a solderless system used to prototype electronics and test circuit designs on a temporary basis. Most electronic components in electronic circuits may be connected by slipping their leads or terminals into holes and connecting them with. The metal strips underneath the breadboard link the holes on the top of the board.|
|MicroPython is a complete bare-metal Python compiler and runtime. You get an interactive prompt (the REPL) that allows you to run and import scripts from the built-in filesystem. It also provides the ability to execute commands immediately. For a better user experience, the REPL includes features such as history, tab completion, auto-indent, and paste mode.|
MicroPython tries to be as similar to regular Python as possible. It provides modules for accessing low-level hardware in addition to integrating a range of key Python libraries.
|Thonny is the IDE, which provides |
Python development environment along
Serial input/output reading capabilities
It comes pre-installed with Python 3.7, so all you have to do is update it and you’re able to practice programming. (A different Python installation can be used as well.) The initial user interface is devoid of any functionality that may be distracting to newcomers.
How do Ultrasonic Sensors Work?
Ultrasonic sensors detect target proximity or range by calculating the time it takes for ultrasound waves to travel forward and reflect from a solid object.
Sound is made up of oscillating waves traveling through a medium. The small band of sound spectrum (frequency range) audible to the human ear is referred to as “Acoustic” range (25hz to 4khz).
|Infrasound||Sounds of very low frequency. Infrasound frequency is between 0Hz to 25Hz.|
|Ultrasound||Sounds with frequency higher than 20khz. Since it is inaudible to the human ear, it is more accurate in short distances|
Ultrasonic Distance Calculation Algorithm
We can approximate the distance using the following formulae as we know the time and speed of sound.
Distance = Speed x Round trip time x 0.5
Speed of Sound is 343m/s at sea level.
Since the time we measured above is the time it takes for the ultrasonic pulse to cover the distance to the object and back, we must divide it by two. In other words, we just want to see how far away the object is!
Ultrasonic Sensor Hardware Setup on Raspberry Pi Pico: –
- Ultrasonic sensor(HC-SR04P) used is compatible with Raspberry Pi Pico GPIO’s 3V logic. HC-SR04P and HC-SR04+ are 3V and 5V logic compatible, making them suitable for Raspberry Pi, Pi, and Arduino projects.
- Using the breadboard, attach the HC-SR04P ultrasonic sensor: –
- Ground (GND), Echo Pulse Output (ECHO), Spike Pulse Input (TRIG), and 5V Supply are the four pins on the HC-SR04 Ultrasonic sensor (Vcc). We use our Raspberry Pi Pico to transmit an input signal to TRIG. It then activates the sensor to send an ultrasonic wave. And lastly we power the module with Vcc and ground it with GND.
- IMPORTANT – On the HC-SR04, the sensor output signal (ECHO) is rated at 5V. On the other hand, the value of the input pin on the GPIO, is 3.3V. But if you send a 5V signal into the unprotected 3.3V input port, your GPIO pins may be destroyed. Therefore to stop this, we’ll use a two-resistor voltage divider circuit to lower the sensor output voltage to a level that our Raspberry Pi Pico can accommodate.
How to Convert Sensor Output from 5V to 3.3V:
Reducing the Sensor output from 5V to 3.3V requires a Voltage Divider. It consists of two resistors (R1 and R2) connected in series to a voltage source (Vin). But it needs to be reduced to our output voltage (Vout). Hence, in our circuit, Vin will be ECHO, and it we should reduce it from 5V to 3.3V.
- We can use the circuit and basic equation given below in a variety of situations where a voltage has to be lowered. Simply catch 1 x 1k and 1 x 2k resistors.
- Vout = Vin × R2/ (R1+R2)
- Without going into too much detail on the arithmetic, we just need to measure one resistor value because the dividing ratio is what matters. We know our input voltage (5V) and necessary output voltage (3.3V), so we can reduce the voltage with any mixture of resistors. I had a lot of extra 1k resistors on hand, so I wanted to use one of them as R1 in the circuit.
- Hence the equation is as follows
3.3/5 = R2/ (1000 + R2)
Ans will be 1941 = R2
As a consequence, we’ll use a 1k resistor for R1 and a 2k resistor for R2!
Ultrasonic Sensor Circuit Assembly
- Using a male-to-male jumper cable, attach the Raspberry Pi Pico’s 3V3 pin to the VCC pin of the ultrasonic sensor.
- Then, using a jumper cable, attach a GND pin on the Raspberry Pi Pico to the GND pin of the ultrasonic sensor.
- Later, connect the ultrasonic sensor’s Trigger pin to the Raspberry Pi Pico’s GPIO pin 3.
- Link the ultrasonic sensor’s Echo pin to the Raspberry Pi Pico’s GPIO pin 2 with resistors R1.
- Finally, link the GND rail using R2 with R1. But, do leave a space between two resistors.
Ultrasonic Sensor Software Setup on Raspberry Pi Pico:
We need to write a Python script to detect distance now that we’ve attached our Ultrasonic Sensor to our Raspberry Pi Pico.
Until the Ultrasonic sensor output (ECHO) is activated, in which case it will output 5V (3.3V with our voltage divider). As a result, one GPIO pin acts as an output to activate the sensor. Further, the other should be set as an input to detect the ECHO voltage transition.
Steps for software setup
- Import the Pin class in python program. This is used to manage GPIO pins
- Import utime library from system library for time-based features.
from machine import pin import utime
- As a result this creates two new items – trigger, and echo.
- These artifacts set up the Pico’s GPIO pins to work with the ultrasonic sensor. For example, we use a trigger pin to transmit a current pulse. Hence, in this case, our trigger pin is an output pin The Echo is an entry since it absorbs the mirrored signal.
trigger = pin(3,pin.OUT) echo = pin(2, pin.IN)
Create a python function ultra() that contains the code needed to take a reading from Sensor.
def ultra (): -
Pull the trigger pin all the way down to make sure it is not working, and then wait for two microseconds.
While pushing the pin down, pull it high for five microseconds. As a result this will cause the ultrasonic sensor to give a short pulse before turning it off.
trigger.high() utime.sleep_us(5) trigger.low()
To search the echo pin, build a while loop. Then check for signs of an echo pulse. But if it doesn’t detect a pulse, set a vector (signaloff) to a timestamp in microseconds.
while echo.value() == 0: - signaloff = utime.ticks_us()
Create a new while loop to check if an echo has been obtained this time. Note that the latest timestamp in microseconds would be saved to the signalon vector.
while echo.value() ==1: - signalon = utime.ticks_us()
Create a new attribute, timepassed, to store the cumulative time it took for the pulse to leave the sensor. Reach the object, and then return as an echo to the sensor.
timepassed = signalon – signaloff
Make a new variable called distance.
This variable stores the response to the equation. We divide the result of the equation by two so we don’t need the entire journey distance, only the distance from the object to the sensor. The speed of sound (343.2 m/s, or 0.0343 cm per microsecond) is multiplied by the journey time (timepassed).
distance = (timpassed * 0.0343) / 2
To the Python Shell, send a message indicating the radius.
print(“The object can be seem from a distance of”,distance, “cm”)
We now exit the function and construct a loop that will execute the function every second.
while true: - ultra() utime.sleep(1)
from machine import pin import utime trigger = pin(3,pin.OUT) echo = pin(2, pin.IN) def ultra (): - trigger.low() utime.sleep_us(2) trigger.high() utime.sleep_us(5) trigger.low() while echo.value() == 0: - signaloff = utime.ticks_us() while echo.value() ==1: - signalon = utime.ticks_us() timepassed = signalon – signaloff distance = (timpassed * 0.0343) / 2 print(“The object can be seen from a distance of”,distance, “cm”) while true: - ultra() utime.sleep(1)
Lastly save the file as code.py on the Raspberry Pi Pico and run it by clicking the green arrow. As a result, the gap will be written per second in the Python Shell.
Python progam is space sensistive. any extra space or tab-space leads to run-time errors.
After a few seconds of settling, the sensor will record your distance!
This concludes the discussion. It may be used in a variety of areas, but those that need to measure longer distances must use laser measurement instruments, which are far more costly.
For more details, you can refer the video given below.
The only two possible scenarios are: –
1. The pi does not receive the high signal, in which case your software either manages it, fails, or runs indefinitely while it is waiting for a high signal.
2. Since the pi knows the signal is high, there is no fault caused by the pi, wiring, or sensor.
If you want your distances to be precise, you might build a calibration curve for your sensor.
NOTE: – Remember that you’re calculating the distance, so the speed of sound through the air at atmospheric temperature must be adjusted appropriately for the environment.
Applications of Ultrasonic sensor
We learned how to attach an HC-SR04 Ultrasonic Sensor to a Raspberry Pi Pico in this project. Purposes of this setup is as follows:
- Avoiding Obstacles
- Proximity Detection: – It is a technique for detecting objects that are close to each other.
- Measurement of Distance
- Range Finder
An ultrasonic sensor uses ultrasonic sound waves to determine the distance between a target object and also transforms the reflected sound into an electrical signal. Ultrasonic waves propagate faster than detectable sound waves (i.e. the sound that humans can hear).
The range of this Ultrasonic Sensor appears limited but it is adequate for its applications, such as proximity detection and obstacle avoidance.