Distance Measurement using an Ultrasonic Sensor

What is an Ultrasonic Sensor?

An ultrasonic sensor is a device that is used to measure distance by sending out a sound and listening for the echo of the sound when it reflects of an object. The amount of time that it takes for the echo to return to the receiver is a measure of the distance of the object from the sensor. In the immortal words of Batman, it’s the same principle as a… <pause> submarine (sending out a ping and listening for the reflection). Yes, it was actually Lucius Fox that said ‘Submarine’ in the movie, but you get the idea. The sound itself is at a frequency greater than that which humans can hear (greater than 20kHz) and as such it us referred to as an ultrasonic noise.

In this case, the sensor itself is a compact device that is popular for applications in robotics and cameras.

Ultrasonic Sensor Package HC-SR04P

In industry they are widely used for liquid level detection and in cars to sound an alert when you get too close to an object.

How does an Ultrasonic Sensor Work?

Ultrasonic distance sensors use a transmitter to emit high frequency sound. The sound reflects off any object it strikes and returns to a receiver. We can think of the transmitter as a speaker and the receiver as a microphone.

Ultrasonic Distance Measurement

Based on the time difference between the emission of the sound and its return it is able to represent the distance between the object and the sensor.

The sensor we will be using is a HC-SR04P ultrasonic sensor. Be aware that there are two practically identical sensors of this type available. An HC-SR04 and an HC-SR04P The HC-SR04 is designed to work with a 5V supply and to use logic levels that are higher than the compatible input and output from the Pico (although they might work, I wouldn’t recommend it). The connection diagrams shown here are for the simpler HC-SR04P, but we will examine an alternative connection method for an HC-SR04 as well.

This sensor can provide an accurate distance measurement to objects between about 2cm to 4m with a resolution of about 3mm. The sound that is emitted is at 40kHz, and as such well above the limit of human hearing. However, there are a range of animals that could potentially hear a noise at that frequency, including bats, cats, dogs, seals, sea-lions and a range of dolphins and porpoises.

The HC-SR04P uses piezoelectric elements (ultrasonic transducers) in their sensor components. One will transmit a certain frequency of sound (like a speaker) when a signal is applied and the other will generate an electrical output when it receives a sound of a certain frequency (like a microphone).

The HC-SR04P is triggered with an applied signal and a sequence of eight 40kHz pulses are generated by the transmitter.

Ultrasonic Distance Transmission

At the same time that the pulses are transmitted, the HC-SR04P’s ‘Echo’ pin is set to high

The pulses are reflected off an object back to the receiver portion of our sensor

Ultrasonic Distance Reflection

When the receiver collects the pulses, the ‘Echo’ pin is set to low and what we are left with is a pulse from our ‘Echo’ pin which has a width dependant on the distance of the object.

If the pulses don’t get reflected back to our receiver (i.e. there isn’t an object to measure) the ‘Echo’ pin will automatically go low after 38ms.

The time limits for receiving the pulses back are between 150µs and 25ms. These are the bounds for our ‘Echo’ signal. A 150µs ‘Echo’ signal corresponds to 2cm and 25ms is 4m.

12ms Echo

The distance from the sensor to the reflecting object can be found by multiplying the time that the echo pin was high (represented as 12ms in the diagram) by the speed of sound (340m/s) and dividing by 2 (since the sound travelled out and back). Therefore;

calculating the distance

Our object is 2.04 metres away!

Connecting an Ultrasonic Sensor Up to the Pico

As mentioned earlier, there are two almost identical models of this particular ultrasonic sensor. The HC-SR04 which works with 5V supply and logic, and the HC-SR04P which will work with supply and logic levels from 3.0V to 5.5V. For the Pico it will be easier to work with the HC-SR04P which will only require four connections. 3.3V power (Vcc), ground (Gnd), Trigger (Trig) and Echo (Echo). The following connections are used for this example;

  • HC-SR04 Vcc to the 3V3(OUT) (pin 36) on the Pico (Red)
  • HC-SR04 Gnd to Ground (GND) (pin 33) on the Pico (Black)
  • HC-SR04 Trig to GP28 (pin 34) on the Pico (Orange)
  • HC-SR04 Echo to GP27 (pin 32) on the Pico (Brown)
HC-SR04P Sensor Connected to the Pico

If we wanted to use the 5V supplied HC-SR04 we would want to incorporate a level shifter into the circuit to reduce or increase the signal levels between the devices. The connection would look something like the following;

HC-SR04 Sensor Connected to the Pico

Or for those who prefer a more real-world example…

Ultrasonic Sensor Connected to the Pico (for reals)

Code

The code below is pretty simple and relies on setting the trigger and echo pins, sending the trigger pulse, measuring the echo pulse and then printing the result.

from machine import Pin
import time

trig=Pin(28, Pin.OUT)
echo=Pin(27, Pin.IN)

while True:
     # Send the trigger
    trig.high()
    time.sleep_us(11)
    trig.low()
    
    #Wait for the echo
    while (echo.value()==0):
        pass
    lastreadtime=time.ticks_us() # record when echo went high
    while (echo.value()==1):
        pass # wait for echo to finish
    echotime=time.ticks_us()-lastreadtime # how long was the echo pulse

    # Print out the distance
    if echotime>37000:
        print("No obstacle in range")
    else:
        distance = (echotime * 0.034) / 2
        print(f"Distance : {distance} cm")
    time.sleep_ms(500)