An ultrasonic sensor is a device that uses sound waves and the reflection of these same waves (echoes) to measure distance. The frequency or pitch of the emitted wave can be set by changing its carrier signal in Hertz, which determines how far it goes before bouncing back off an object up ahead.

This Technique is used by bats who emit high-pitched sounds pulse for mapping obstacles around them -most ultrasonic sensors are limited up to 5 meters as opposed to Bat Sonar capable of mapping surroundings upto 70m. But the basic of measurement remains same in both the cases : Obstacle Distance = Time spent reflecting soundwave *0.5 * Speed of sound. –Sound travels at 330m/s.

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.

Raspberry Pi Pico with HC-SR04 ultrasonic distance sensor.

HC-SR04 Consists of 2 modules.

Ultrasonic Transmitter: One or two ultrasonic transmitters emit a high-frequency sound that bounces off any solid objects in the region. This is picked up by the sensor’s receiver which has been modified to process these return signals and determine how far away from an object it is using some clever arithmetic.
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.

Bill of materials

Material nameImage Description
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.
HC-SR04
(Hardware)
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.
Breadboard
(Hardware)
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
(Software)
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
(Software)
Thonny is the IDE, which provides
Python development environment along
Serial input/output reading capabilities
Debug environment.
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).

InfrasoundSounds of very low frequency. Infrasound frequency is between 0Hz to 25Hz.
UltrasoundSounds 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 330m/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: –

  1. 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.
  2. Using the breadboard, attach the HC-SR04P ultrasonic sensor: –
  3. 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.
  4.  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.

  1. 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.
  2. Vout = Vin × R2/ (R1+R2)
  3. 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.
  4. 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

  1. Using a male-to-male jumper cable, attach the Raspberry Pi Pico’s 3V3 pin to the VCC pin of the ultrasonic sensor.
  2. Then, using a jumper cable, attach a GND pin on the Raspberry Pi Pico to the GND pin of the ultrasonic sensor.
  3. Later, connect the ultrasonic sensor’s Trigger pin to the Raspberry Pi Pico’s GPIO pin 3.
  4. Link the ultrasonic sensor’s Echo pin to the Raspberry Pi Pico’s GPIO pin 2 with resistors R1.
  5. 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

Step 1:

  • 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)

Step 2:

Create a python function ultra() that contains the code needed to take a reading from Sensor.

def ultra (): -

Step 3:

Pull the trigger pin all the way down to make sure it is not working, and then wait for two microseconds.

trigger.low()
utime.sleep_us(2)

Step 4:

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()

Step 5:

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()

Step 6:

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()

Step 7:

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

Step 8:

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

Step 9:

To the Python Shell, send a message indicating the radius.

print(“The object can be seem from a distance of”,distance, “cm”)

Step 10:

We now exit the function and construct a loop that will execute the function every second.

while true: -
ultra()
utime.sleep(1)

Complete Micropython code

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.0330) / 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 output 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.

Program Results

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

In this project, we learned how to attach an HC-SR04 Ultrasonic Sensor to a Raspberry Pi Pico. The purposes of the setup are as follows:

  • 1) Avoiding Obstacles – by detecting objects that could be in its way and not running into them;
  • 2) Proximity Detection: It is a technique for detection whether or not two targets are close enough together (within range);
  • 3) Measurement of Distance – measuring just how far away the target object is from your sensor’s location/
  • 4 ) Range Finder – able to measure distance between you and obstacles reliably without having much difficulty.

The range of this Ultrasonic Sensor appears limited but it is adequate for its applications, such as proximity detection and obstacle avoidance.

2.3 3 votes
Article Rating
Previous articleHow to add a reset button to your Raspberry Pi Pico
Next articleMycroft Mark-II – The Secret HW FAR Field Mic Array
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments