Raspberry Pi Pico
HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 is an ultrasonic distance sensor that is widely used with microcontroller projects. You often see them connected to robot vehicles to detect obstacles in the vehicle's path. It has a range from 2cm up to 4.5m although, more often than not, it is used for distances nearer than a couple of metres.

Pico Circuit

To use the sensor with the Pico, you need to look for one that is specifically labelled as working with 3V logic. The one I used came from 4tronix and is very good value for money at just over £2.

Pico Circuit

In my test circuit I connected power and ground to 3V and GND. I connected the echo pin to GP16 and the trigger pin to GP17. With these sensors, you toggle the trigger pin to send out an ultrasonic signal and measure the time it takes to receive the reflected sound. This can then be converted to a distance.

from machine import Pin, time_pulse_us
from time import sleep

echo = Pin(16, Pin.IN)
trigger = Pin(17, Pin.OUT)

def get_distance(e, t):
    d = time_pulse_us(e,1,11600)
    if d>0:
        return d/58
        return d

I tested this by making calls to the function in the shell, placing my hand at different distances from the sensor and checking that the result matched my estimate of the distance.

Pico Circuit