The HC-SR04 ultrasonic distance sensor works like a sonar. Let’s see in this tutorial how to connect the HC-SR04 to a Raspberry Pi Pico. We’ll also write a script in MicroPython to calculate a measured distance based on the input data of the sensor.
- Prepare the hardware
– First you need a computer to run Thonny. In this tutorial we’ll use a Raspberry Pi 4 as our computer. And Thonny is a user-friendly Python IDE to interact with the Raspberry Pi Pico board. If you never used Thonny to program the Raspberry Pi Pico, before continuing, you better have a look at our tutorial “How to start programming the Raspberry Pi Pico“.
– Next you need an USB cable with micro-USB plug.
– You also need a Raspberry Pi Pico of course. For this tutorial you need pin headers soldered to the GPIO-pins of your board.
And finally you’ll need some extra components :
– a breadboard (we are using a 400 points breadboard)
– an HC-SR04 ultrasonic sensor
– a 1k Ohm and a 2k Ohm resistor
– Dupont jumper wires
Visit our shop if you miss any components.
- Get to know the HC-SR04 ultrasonic sensor
The HC-SR04 ultrasonic sensor uses the sonar principle to determine the distance to an object. It offers a contactless measurement with good accuracy and stable readings. On the module we find an ultrasonic transmitter and a receiver. The sensor has a range of 2 to 400 cm. The accuracy of the measurement is +/- 0.5 cm.
The sensor uses ultrasonic sound signals to define the distance:
– The transmitter sends an audio signal in the direction of the object.
– When the signal reaches the object, it is reflected back to the sensor.
– The receiver can detect the reflected signal.
We can calculate the time difference between the time when the transmitter sends the signal and the time when the receiver picks up the signal. Since the speed of the sound is known (343.3 m / s or 34330 cm / s) we can now calculate the distance:
distance = speed * time , or in our case:
distance = 34330 * time / 2 , or distance = 17165 * time
Note: Since the measured time takes into account the distance from the sensor to the object and the distance from the object to the sensor, we must divide this observed time by 2.
Be careful ! Before starting to connect components to the GPIO pins of your Raspberry Pi Pico, make sure it is not connected to your computer.
- Setup the hardware part
– place the HC-SR04 sensor onto the breadbord as shown in the picture below
– connect the VCC pin of the sensor with a 5V pin (red wire)
– connect the Trig pin of the sensor to GP17 (green wire)
– connect the Echo pin of the sensor to the 1kOhm resistor (yellow wire)
– connect the other end of the 1kOhm resistor to GP16
– connect the GND of the sensor to the “-” row of the breadboard (black wire)
– connect a GND pin of the Pico to the “-” row of the breadboard (black wire)
– insert the 2kOhm resistor between GP16 and the “-” row
- Write the code
The aim here is to write a very basic MicroPython script that computes every second a distance in cm between the ultrasonic sensor and an object.
Now, open Thonny and write or paste following code in the IDE:
from machine import Pin
trig = Pin(17, Pin.OUT)
echo = Pin(16, Pin.IN, Pin.PULL_DOWN)
pulse_start = time.ticks_us()
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17165 / 1000000
distance = round(distance, 0)
Be careful, MicroPython is whitespace-sensitive. Don’t remove the “tabs”.
Some explanations about the code :
from machine import Pin: to partially import the machine module to have access to the GPIO pins.
import time: to import the time module. This will allow us to use time-related tasks.
trig= Pin(17, Pin.OUT): here we declare the trigger sensor pin (=GP17) as an output pin.
echo= Pin(16, Pin.IN, Pin.PULL_DOWN):here we declare the echo sensor pin (=GP16) as an input pin. To avoid a ‘floating’ input, we use an internal pull-down resistor.
while True:is an infinitive loop (until we stop the program).
trig.value(0): to make sure the sensor does not emmit any sound
time.sleep(0.1): we wait for a short period to settle the sensor
trig.value(1): to let the sensor emit a sound
time.sleep_us(2): emitting for a very short time : 2 microseconds
trig.value(0): stop emitting the sound
Now the sensor produces a pulse whose duration is proportional to the measured distance. So, we need to record the start and end timestamps. And then we make the difference to calculate the elapsed time.
pulse_start = time.ticks_us(): here we’ll keep the time as long as the sensor doesn’t produce the pulse.
pulse_end = time.ticks_us(): and here we’ll keep the time as long as the sensor does produce the pulse.
pulse_duration = pulse_end - pulse_startwe calculate the time difference between both timestamps
distance = pulse_duration * 17165 / 1000000: we calculate the distance based on the time and convert microseconds to seconds (see explanation in previous paragraph).
Finally, we round the result and print it.
- Run your script
Now, it’s time to save your script. You can either save it on your computer or on your Pico board.
Then, click on the Run button of the Thonny IDE. And point the sensor to an object with a flat surface. You will see the distance between the sensor and the object appear on the screen as a result.
Be careful with other objects nearby. These could also send an echo. Which would then give you incorrect measured values.
Congratulations! With this setup you do understand now the principle of how some distance meters function. You can further use the script to process the result in an application where you want to measure or monitor a certain distance yourself. Have fun with it!
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?