Learn how to use the HC-SR04 Ultrasonic Sensor with the Raspberry Pi Pico to get the distance to an object programmed using Arduino IDE. This tutorial covers how to wire the sensor to the RPi Pico board, a simple example sketch to calculate and get the distance to an object, and a quick, simple project to display the distance on an OLED screen.

New to the Raspberry Pi Pico? Get started with the Raspberry Pi Pico here.
Table of Contents:
- Introducing the HC-SR04 Ultrasonic Sensor
- HC-SR04 Ultrasonic Sensor Technical Data
- HC-SR04 Ultrasonic Sensor Pinout
- How Does the HC-SR04 Ultrasonic Sensor Work?
- RPi Pico with HC-SR04 Ultrasonic Sensor – Wiring Diagram
- Getting Distance to an Object – Arduino Code (RPi Pico + HC-SR04)
- Display Distance (HCSR04) on OLED Display
Raspberry Pi Pico with Arduino IDE
You need to install the Raspberry Pi Pico boards on Arduino IDE and you must know how to upload code to the board. Check out the following tutorial first if you haven’t already:
Introducing the HC-SR04 Ultrasonic Sensor
The HC-SR04 ultrasonic sensor uses sonar to determine the distance to an object. This sensor reads from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), which is good for most hobbyist projects. In addition, this particular module comes with ultrasonic transmitter and receiver modules.
The following picture shows the HC-SR04 ultrasonic sensor.

The next picture shows the other side of the sensor.

Want an alternative for the HC-SR04 ultrasonic sensor? Check out the RCWL-0516 Radar Proximity Sensor:
Where to Buy HC-SR04 Ultrasonic Sensor?
You can check the Ultrasonic Sensor HC-SR04 on Maker Advisor to find the best price:
HC-SR04 Ultrasonic Sensor Technical Data
The following table shows the key features and specs of the HC-SR04 ultrasonic sensor. For more information, you should consult the sensor’s datasheet.
Power Supply | 5V DC |
Working Current | 15 mA |
Working Frequency | 40 kHz |
Maximum Range | 4 meters |
Minimum Range | 2 cm |
Measuring Angle | 15º |
Resolution | 0.3 cm |
Trigger Input Signal | 10uS TTL pulse |
Echo Output Signal | TTL pulse proportional to the distance range |
Dimensions | 45mm x 20mm x 15mm |
HC-SR04 Ultrasonic Sensor Pinout
Here’s the pinout of the HC-SR04 Ultrasonic Sensor.
VCC | Powers the sensor (5V) |
Trig | Trigger Input Pin |
Echo | Echo Output Pin |
GND | Common GND |
How Does the HC-SR04 Ultrasonic Sensor Work?
The ultrasonic sensor uses sonar to determine the distance to an object. Here’s how it works:
- The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
- The sound travels through the air. If it finds an object, it bounces back to the module.
- The ultrasound receiver (echo pin) receives the reflected sound (echo).

Taking into account the sound’s velocity in the air and the travel time (elapsed time since the transmission and reception of the signal) we can calculate the distance to an object. Here’s the formula:
distance to an object = ((speed of sound in the air)*time)/2
- speed of sound in the air at 20ºC (68ºF) = 343m/s
Parts Required

To complete this tutorial, you need the following parts:
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
RPi Pico with HC-SR04 Ultrasonic Sensor – Wiring Diagram
Wire the HC-SR04 ultrasonic sensor to the RPi Pico board as shown in the following schematic diagram. We’re connecting the Trig pin to GPIO 27 and the Echo pin to GPIO 28, but you can use any other suitable pins.

Ultrasonic Sensor | RPi Pico |
VCC | VBus (5V) |
Trig | GPIO 27 |
Echo | GPIO 28 in series with a 1kOhm resistor |
GND | GND |
Recommended reading: Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained.
Code – Getting Distance to an Object using the HC-SR04 Ultrasonic Sensor and the RPi Pico
The following sketch is a simple example of how you can get the distance between the sensor and an object using the RPi Pico board programmed with the Arduino core.
/*********
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-hc-sr04-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
const int trigPin = 27;
const int echoPin = 28;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
delay(1000);
}
Upload the code to your board and it will work straight away. Continue reading if you want to learn how the code works or skip to the demonstration section.
How the Code Works
First, define the trigger and the echo pins.
const int trigPin = 27;
const int echoPin = 28;
In this example, we’re using GPIO 27 and GPIO 28. But you can use any other suitable GPIOs—read Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained.
The SOUND_SPEED variable saves the velocity of sound in the air at 20ºC. We’re using the value in cm/uS.
#define SOUND_SPEED 0.034
The CM_TO_INCH variable allows us to convert distance in centimeters to inches.
#define CM_TO_INCH 0.393701
Then, initialize the following variables.
long duration;
float distanceCm;
float distanceInch;
The duration variable saves the travel time of the ultrasonic waves (time elapsed since transmission and reception of the pulse wave). The distanceCm and distanceInch, as the names suggest, save the distance to an object in centimeters and inches.
setup()
In the setup(), initialize a serial communication at a baud rate of 115200 so that we can print the measurements on the Serial Monitor.
Serial.begin(115200); // Starts the serial communication
Define the trigger pin as an OUTPUT—the trigger pin emits the ultrasound. And define the echo pin as an INPUT—the echo pin receives the reflected wave and sends a signal to the RPi Pico that is proportional to the travel time.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
loop()
In the loop(), the following lines produce a 10uS HIGH pulse on the trigger pin—this means the pin will emit an ultrasound. Note that before sending the pulse, we give a short LOW pulse to ensure you’ll get a clean HIGH pulse.
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
We use the pulseIn() function to get the sound wave travel time:
duration = pulseIn(echoPin, HIGH);
The pulseIn() function reads a HIGH or a LOW pulse on a pin. It accepts as arguments the pin and the state of the pulse (either HIGH or LOW). It returns the length of the pulse in microseconds. The pulse length corresponds to the time it took to travel to the object plus the time it took the way back.
Then, we simply calculate the distance to an object, taking into account the sound speed.
distanceCm = duration * SOUND_SPEED/2;
Convert the distance to inches:
distanceInch = distanceCm * CM_TO_INCH;
And finally, print the results on the Serial Monitor.
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
Demonstration
Upload the code to the Raspberry Pi Pico.
To upload code to the Raspberry Pi Pico, it needs to be in bootloader mode.
If the Raspberry Pi is currently running MicroPython firmware, you need to manually put it into bootloader mode. For that, connect the Raspberry Pi Pico to your computer while holding the BOOTSEL button at the same time. A new mass storage device window will open on your computer. You can ignore it and close that window.

For future uploads using Arduino IDE, the board should go automatically into bootloader mode without the need to press the BOOTSEL button.
Now, open the top drop-down menu and click on Select other board and port…

Select the Raspberry Pi Pico model you’re using.
The COM port might not show up on your first upload, so you need to tick the Show all ports option. Then, select the COM port.

Now, you can upload the code.

You should get a success message.

After uploading the code, open the Serial Monitor at a baud rate of 115200.

The distance to the closest object will be printed in the Serial Monitor.

Display Distance (HCSR04) on OLED Display (RPi Pico with Arduino IDE)
Now that you know how to get the distance to the closest object using an HC-SR04 ultrasonic sensor, we’ll display the sensor readings on an OLED display.

Recommended reading: Raspberry Pi Pico: SSD1306 OLED Display (Arduino IDE).
Parts Required
Here’s a list of the parts required to complete this example:
- HC-SR04 Ultrasonic Sensor
- Raspberry Pi Pico (any model)
- 1kOhm resistor
- 0.96 inch I2C OLED Display SSD1306
- Breadboard
- Jumper wires
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Schematic Diagram
Add an I2C OLED display to the previous circuit. We’re connecting SDA to GPIO 4, and SCL to GPIO 5. You can follow the next schematic diagram:

Install the SSD1306 Library
In the Arduino IDE, go to Sketch > Include Library > Manage Libraries.
Then, search for Adafruit SSD1306 and install the library.

Also, install any other required dependencies.
Display the Distance On OLED Display
Copy the following code to the Arduino IDE. This code gets the distance of the HC-SR04 sensor to an object, and displays the result in an OLED display.
/*********
Rui Santos & Sara Santos - Random Nerd Tutorials
Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-hc-sr04-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const int trigPin = 27;
const int echoPin = 28;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
int distanceCm;
int distanceInch;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
delay(500);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
display.clearDisplay();
display.setCursor(0, 25);
//Display distance in cm
display.print(distanceCm);
display.print(" cm");
// Display distance in inches
/* display.print(distanceInch);
display.print(" in");*/
display.display();
delay(500);
}
How the Code Works
Start by including the required libraries for the OLED display:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Define the width and height of the OLED display. We’re using a 128×64 OLED display:
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Create an Adafruit_SSD1306 object called display to handle the OLED display.
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);
Define the pins that the HC-SR04 sensor is connected to.
const int trigPin = 27;
const int echoPin = 28;
Create variables to save the distance and the duration between the transmission and reception of the sound waves.
long duration;
int distanceCm;
int distanceInch;
setup()
In the setup(), initialize a serial communication at a baud rate of 115200 so that we can print the results on the Serial Monitor.
Serial.begin(115200);
Define the trigger pin as an OUTPUT and the echo pin as an INPUT.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Initialize the OLED display:
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
Set the font size and color for the display.
display.setTextSize(2);
display.setTextColor(WHITE);
loop()
In the loop() is where we’ll get the distance and display it on the OLED.
Get the distance (we’ve already explained in the previous section how to calculate the distance).
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
Print the distance on the Serial Monitor.
// Prints the distance on the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
Clear the display in each loop() to write new readings.
display.clearDisplay();
Set the display cursor to (0, 25).
display.setCursor(0, 25);
The following lines print the distance in centimeters in the OLED display.
// Display static text
display.print(distanceCm);
display.print(" cm");
Comment the previous lines and uncomment the following lines if you want to display the readings in inches.
/* Display distance in inches
display.print(distanceInch);
display.print(" in");*/
Lastly, call display.display() to actually show the readings on the OLED.
display.display();
The distance is updated every 500 milliseconds.
delay(500);
Demonstration
Upload the code to the Raspberry Pi Pico.
The distance to the closest object will be printed on the OLED screen.

Wrapping Up
The HC-SR04 Ultrasonic Sensor allows us to determine the distance to an object. In this tutorial, you’ve learned how to use the HC-SR04 with the RPi Pico. We have tutorials for other popular sensors with the RPi Pico using Arduino IDE that you may like:
- Raspberry Pi Pico with Anemometer: Measure Wind Speed (Arduino IDE)
- Raspberry Pi Pico: BME680 Environmental Sensor (Arduino IDE)
- Raspberry Pi Pico: Detect Motion using a PIR Sensor (Arduino IDE)
- Raspberry Pi Pico: BME280 Get Temperature, Humidity, and Pressure (Arduino IDE)
- Raspberry Pi Pico: RCWL-0516 Microwave Radar Proximity Sensor (Arduino IDE)
- Raspberry Pi Pico: SSD1306 OLED Display (Arduino IDE)
- Raspberry Pi Pico: 20+ Free Guides for Sensors and Modules
You can check all our Raspberry Pi Pico tutorials and guides here.