{"id":171169,"date":"2025-08-26T16:28:55","date_gmt":"2025-08-26T16:28:55","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=171169"},"modified":"2025-08-26T16:28:57","modified_gmt":"2025-08-26T16:28:57","slug":"raspberry-pi-pico-hc-sr04-arduino","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-hc-sr04-arduino\/","title":{"rendered":"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (Arduino IDE)"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (Arduino IDE)\" class=\"wp-image-171186\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?w=1920&amp;quality=100&amp;strip=all&amp;ssl=1 1920w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?resize=1536%2C864&amp;quality=100&amp;strip=all&amp;ssl=1 1536w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgreen\"><strong>New to the Raspberry Pi Pico?<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\" title=\"\">Get started with the Raspberry Pi Pico here<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#ultrasonic-sensor-intro\" title=\"\">Introducing the HC-SR04 Ultrasonic Sensor<\/a><\/li>\n\n\n\n<li><a href=\"#ultrasonic-sensor-technical-data\" title=\"\">HC-SR04 Ultrasonic Sensor Technical Data<\/a><\/li>\n\n\n\n<li><a href=\"#ultrasonic-sensor-pinout\" title=\"\">HC-SR04 Ultrasonic Sensor Pinout<\/a><\/li>\n\n\n\n<li><a href=\"#ultrasonic-sensor-how-it-works\" title=\"\">How Does the HC-SR04 Ultrasonic Sensor Work?<\/a><\/li>\n\n\n\n<li><a href=\"#wiring\" title=\"\">RPi Pico with HC-SR04 Ultrasonic Sensor &#8211; Wiring Diagram<\/a><\/li>\n\n\n\n<li><a href=\"#RPi-Pico-get-distance-HCSR04\" title=\"\">Getting Distance to an Object &#8211; Arduino Code (RPi Pico + HC-SR04)<\/a><\/li>\n\n\n\n<li><a href=\"#display-distance-oled\" title=\"\">Display Distance (HCSR04) on OLED Display<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"rpi-pico-arduino-ide\">Raspberry Pi Pico with Arduino IDE<\/h2>\n\n\n\n<p>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\u2019t already:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/programming-raspberry-pi-pico-w-arduino-ide\/\">Programming Raspberry Pi Pico with Arduino IDE<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ultrasonic-sensor-intro\">Introducing the HC-SR04 Ultrasonic Sensor<\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>The following picture shows the HC-SR04 ultrasonic sensor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Front.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR04 Ultrasonic Sensor Module Distance Measurement Component Part Front\" class=\"wp-image-104465\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Front.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Front.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>The next picture shows the other side of the sensor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Back.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR04 Ultrasonic Sensor Module Distance Measurement Component Part Back\" class=\"wp-image-104464\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Back.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Back.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<div class=\"wp-block-group rntbox rntclgray\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p><strong>Want an alternative for the HC-SR04 ultrasonic sensor?<\/strong> Check out the RCWL-0516 Radar Proximity Sensor: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-rcwl-0516-arduino\/\">Raspberry Pi Pico: RCWL-0516 Microwave Radar Proximity Sensor (Arduino IDE)<\/a><\/li>\n<\/ul>\n<\/div><\/div>\n\n\n\n<p><strong>Where to Buy HC-SR04 Ultrasonic Sensor?<\/strong><\/p>\n\n\n\n<p>You can check the&nbsp;Ultrasonic Sensor HC-SR04 on Maker Advisor&nbsp;to find the best price:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ultrasonic-sensor-technical-data\">HC-SR04 Ultrasonic Sensor Technical Data<\/h2>\n\n\n\n<p>The following table shows the key features and specs of the HC-SR04 ultrasonic sensor. For more information, you should consult the sensor&#8217;s datasheet.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Power Supply<\/strong><\/td><td>5V DC<\/td><\/tr><tr><td><strong>Working Current<\/strong><\/td><td>15 mA<\/td><\/tr><tr><td><strong>Working Frequency<\/strong><\/td><td>40 kHz<\/td><\/tr><tr><td><strong>Maximum Range<\/strong><\/td><td>4 meters<\/td><\/tr><tr><td><strong>Minimum Range<\/strong><\/td><td>2 cm<\/td><\/tr><tr><td><strong>Measuring Angle<\/strong><\/td><td>15\u00ba<\/td><\/tr><tr><td><strong>Resolution<\/strong><\/td><td>0.3 cm<\/td><\/tr><tr><td><strong>Trigger Input Signal<\/strong><\/td><td>10uS TTL pulse<\/td><\/tr><tr><td><strong>Echo Output Signal<\/strong><\/td><td>TTL pulse proportional to the distance range<\/td><\/tr><tr><td><strong>Dimensions<\/strong><\/td><td>45mm x 20mm x 15mm<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ultrasonic-sensor-pinout\">HC-SR04 Ultrasonic Sensor Pinout<\/h2>\n\n\n\n<p>Here&#8217;s the pinout of the HC-SR04 Ultrasonic Sensor.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><span class=\"rnthl rntcred\">VCC<\/span><\/td><td>Powers the sensor (5V)<\/td><\/tr><tr><td><span class=\"rnthl rntcgreen\">Trig<\/span><\/td><td>Trigger Input Pin<\/td><\/tr><tr><td><span class=\"rnthl rntclgray\">Echo<\/span><\/td><td>Echo Output Pin<\/td><\/tr><tr><td><span class=\"rnthl rntcblack\">GND<\/span><\/td><td>Common GND<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ultrasonic-sensor-how-it-works\">How Does the HC-SR04 Ultrasonic Sensor Work?<\/h2>\n\n\n\n<p>The ultrasonic sensor uses sonar to determine the distance to an object. Here&#8217;s how it works:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).<\/li>\n\n\n\n<li>The sound travels through the air. If it finds an object, it bounces back to the module.<\/li>\n\n\n\n<li>The ultrasound receiver (echo pin) receives the reflected sound (echo).<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"453\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/how-ultrasonic-sensor-works-01.png?resize=750%2C453&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"How Ultrasonic Sensor Works\" class=\"wp-image-104535\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/how-ultrasonic-sensor-works-01.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/how-ultrasonic-sensor-works-01.png?resize=300%2C181&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Taking into account the sound&#8217;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&#8217;s the formula:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>distance to an object = ((speed of sound in the air)*time)\/2<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>speed of sound in the air at 20\u00baC (68\u00baF) = <strong>343m\/s<\/strong><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico with HCSR04 Ultrasonic Sensor\" class=\"wp-image-170989\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>To complete this tutorial, you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-2-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico<\/a> (any model)<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">1k Ohm resistor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noreferrer noopener\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"wiring\">RPi Pico with HC-SR04 Ultrasonic Sensor &#8211; Wiring Diagram<\/h2>\n\n\n\n<p>Wire the HC-SR04 ultrasonic sensor to the RPi Pico board as shown in the following schematic diagram. We&#8217;re connecting the Trig pin to <span class=\"rnthl rntcgreen\">GPIO 27<\/span> and the Echo pin to <span class=\"rnthl rntclgray\">GPIO 28<\/span>, but you can use any other suitable pins.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"897\" height=\"576\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-wiring-diagram_bb.png?resize=897%2C576&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico with ultrasonic sensor - wiring diagram\" class=\"wp-image-170994\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-wiring-diagram_bb.png?w=897&amp;quality=100&amp;strip=all&amp;ssl=1 897w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-wiring-diagram_bb.png?resize=300%2C193&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-wiring-diagram_bb.png?resize=768%2C493&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 897px) 100vw, 897px\" \/><\/figure><\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Ultrasonic Sensor<\/strong><\/td><td><strong>RPi Pico<\/strong><\/td><\/tr><tr><td>VCC<\/td><td><span class=\"rnthl rntcred\">VBus<\/span> (5V)<\/td><\/tr><tr><td>Trig<\/td><td><span class=\"rnthl rntcgreen\">GPIO 27<\/span><\/td><\/tr><tr><td>Echo<\/td><td><span class=\"rnthl rntclgray\">GPIO 28<\/span> in series with a 1kOhm resistor<\/td><\/tr><tr><td>GND<\/td><td><span class=\"rnthl rntcblack\">GND<\/span><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>Recommended reading:<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" title=\"\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"RPi-Pico-get-distance-HCSR04\">Code \u2013 Getting Distance to an Object using the HC-SR04 Ultrasonic Sensor and the RPi Pico<\/h2>\n\n\n\n<p>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.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n  Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-hc-sr04-arduino\/\n  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.\n  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*********\/\n\nconst int trigPin = 27;\nconst int echoPin = 28;\n\n\/\/define sound speed in cm\/uS\n#define SOUND_SPEED 0.034\n#define CM_TO_INCH 0.393701\n\nlong duration;\nfloat distanceCm;\nfloat distanceInch;\n\nvoid setup() {\n  Serial.begin(115200); \/\/ Starts the serial communication\n  pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\n  pinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input\n}\n\nvoid loop() {\n  \/\/ Clears the trigPin\n  digitalWrite(trigPin, LOW);\n  delayMicroseconds(2);\n  \/\/ Sets the trigPin on HIGH state for 10 micro seconds\n  digitalWrite(trigPin, HIGH);\n  delayMicroseconds(10);\n  digitalWrite(trigPin, LOW);\n  \n  \/\/ Reads the echoPin, returns the sound wave travel time in microseconds\n  duration = pulseIn(echoPin, HIGH);\n  \n  \/\/ Calculate the distance\n  distanceCm = duration * SOUND_SPEED\/2;\n  \n  \/\/ Convert to inches\n  distanceInch = distanceCm * CM_TO_INCH;\n  \n  \/\/ Prints the distance in the Serial Monitor\n  Serial.print(&quot;Distance (cm): &quot;);\n  Serial.println(distanceCm);\n  Serial.print(&quot;Distance (inch): &quot;);\n  Serial.println(distanceInch);\n  \n  delay(1000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/Arduino\/HC_SR04_Ultrasonic_Basic.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>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 <a href=\"#basic-demonstration\">demonstration section<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>First, define the trigger and the echo pins. <\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const int trigPin = 27;\nconst int echoPin = 28;<\/code><\/pre>\n\n\n\n<p>In this example, we&#8217;re using <span class=\"rnthl rntcgreen\">GPIO 27<\/span> and <span class=\"rnthl rntclgray\">GPIO 28<\/span>. But you can use any other suitable GPIOs\u2014read <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-pinout-gpios\/\" title=\"\">Raspberry Pi Pico and Pico W Pinout Guide: GPIOs Explained<\/a>. <\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">SOUND_SPEED<\/span> variable saves the velocity of sound in the air at 20\u00baC. We&#8217;re using the value in cm\/uS.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define SOUND_SPEED 0.034<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">CM_TO_INCH<\/span> variable allows us to convert distance in centimeters to inches.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define CM_TO_INCH 0.393701<\/code><\/pre>\n\n\n\n<p>Then, initialize the following variables.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>long duration;\nfloat distanceCm;\nfloat distanceInch;<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">duration<\/span> variable saves the travel time of the ultrasonic waves (time elapsed since transmission and reception of the pulse wave). The <span class=\"rnthl rntliteral\">distanceCm<\/span> and <span class=\"rnthl rntliteral\">distanceInch<\/span>, as the names suggest, save the distance to an object in centimeters and inches.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">setup()<\/h3>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, initialize a serial communication at a baud rate of 115200 so that we can print the measurements on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200); \/\/ Starts the serial communication<\/code><\/pre>\n\n\n\n<p>Define the trigger pin as an <span class=\"rnthl rntliteral\">OUTPUT<\/span>\u2014the trigger pin emits the ultrasound. And define the echo pin as an <span class=\"rnthl rntliteral\"> INPUT<\/span>\u2014the echo pin receives the reflected wave and sends a signal to the RPi Pico that is proportional to the travel time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\npinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">loop()<\/h3>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span>, the following lines produce a 10uS <span class=\"rnthl rntliteral\">HIGH<\/span> pulse on the trigger pin\u2014this means the pin will emit an ultrasound. Note that before sending the pulse, we give a short <span class=\"rnthl rntliteral\">LOW<\/span> pulse to ensure you&#8217;ll get a clean <span class=\"rnthl rntliteral\">HIGH<\/span> pulse.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Clears the trigPin\ndigitalWrite(trigPin, LOW);\ndelayMicroseconds(2);\n\/\/ Sets the trigPin on HIGH state for 10 micro seconds\ndigitalWrite(trigPin, HIGH);\ndelayMicroseconds(10);\ndigitalWrite(trigPin, LOW);<\/code><\/pre>\n\n\n\n<p>We use the <span class=\"rnthl rntliteral\">pulseIn()<\/span> function to get the sound wave travel time:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>duration = pulseIn(echoPin, HIGH);<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclgreen\">The <span class=\"rnthl rntliteral\">pulseIn()<\/span> 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.<\/p>\n\n\n\n<p>Then, we simply calculate the distance to an object, taking into account the sound speed.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>distanceCm = duration * SOUND_SPEED\/2;<\/code><\/pre>\n\n\n\n<p>Convert the distance to inches:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>distanceInch = distanceCm * CM_TO_INCH;<\/code><\/pre>\n\n\n\n<p>And finally, print the results on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.print(\"Distance (cm): \");\nSerial.println(distanceCm);\nSerial.print(\"Distance (inch): \");\nSerial.println(distanceInch);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"basic-demonstration\">Demonstration<\/h2>\n\n\n\n<p>Upload the code to the Raspberry Pi Pico.<\/p>\n\n\n\n<p>To upload code to the Raspberry Pi Pico, it needs to be in bootloader mode.<\/p>\n\n\n\n<p>If the Raspberry Pi is currently running MicroPython firmware, <strong>you need to manually put it into bootloader mode<\/strong>. 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.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Bottloader-mode.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Bootloader mode\" class=\"wp-image-130903\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Bottloader-mode.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Raspberry-Pi-Pico-Bottloader-mode.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>For future uploads using Arduino IDE, the board should go automatically into bootloader mode without the need to press the BOOTSEL button.<\/p>\n\n\n\n<p>Now, open the top drop-down menu and click on <strong>Select other board and port&#8230;<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"841\" height=\"232\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Arduino-IDE-2-select-other-board-and-port.png?resize=841%2C232&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"arduino IDE 2 select other board and port\" class=\"wp-image-150047\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Arduino-IDE-2-select-other-board-and-port.png?w=841&amp;quality=100&amp;strip=all&amp;ssl=1 841w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Arduino-IDE-2-select-other-board-and-port.png?resize=300%2C83&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/Arduino-IDE-2-select-other-board-and-port.png?resize=768%2C212&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 841px) 100vw, 841px\" \/><\/figure><\/div>\n\n\n<p>Select the Raspberry Pi Pico model you&#8217;re using.<\/p>\n\n\n\n<p>The COM port might not show up on your first upload, so you need to tick the <strong>Show all ports<\/strong> option. Then, select the COM port.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"699\" height=\"504\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/raspberry-pi-pico-arduino-ide-2-select-com-port.png?resize=699%2C504&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Arduino IDE 2 select Raspberry Pi Pico COM port.\" class=\"wp-image-150048\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/raspberry-pi-pico-arduino-ide-2-select-com-port.png?w=699&amp;quality=100&amp;strip=all&amp;ssl=1 699w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/03\/raspberry-pi-pico-arduino-ide-2-select-com-port.png?resize=300%2C216&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 699px) 100vw, 699px\" \/><\/figure><\/div>\n\n\n<p>Now, you can upload the code.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"36\" height=\"39\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/05\/arduino-ide-2-upload-button.png?resize=36%2C39&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Arduino IDE 2 Upload Button\" class=\"wp-image-146269\"\/><\/figure><\/div>\n\n\n<p>You should get a success message.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"744\" height=\"249\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/05\/RPi-Pico-2-Success-Upload-Arduino-IDE.jpg?resize=744%2C249&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Upload code to Raspberry Pi Pico 2 using Arduino IDE OK\" class=\"wp-image-169997\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/05\/RPi-Pico-2-Success-Upload-Arduino-IDE.jpg?w=744&amp;quality=100&amp;strip=all&amp;ssl=1 744w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/05\/RPi-Pico-2-Success-Upload-Arduino-IDE.jpg?resize=300%2C100&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 744px) 100vw, 744px\" \/><\/figure><\/div>\n\n\n<p>After uploading the code, open the Serial Monitor at a baud rate of 115200. <\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor-testing.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Testing the RPi Pico with HCSR04 Ultrasonic Sensor\" class=\"wp-image-170990\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor-testing.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-HCSR04-ultrasonic-sensor-testing.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>The distance to the closest object will be printed in the Serial Monitor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"666\" height=\"276\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-serial-monitor-arduino-ide.png?resize=666%2C276&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico with ultrasonic sensor - readings displayed on the serial monitor\" class=\"wp-image-171172\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-serial-monitor-arduino-ide.png?w=666&amp;quality=100&amp;strip=all&amp;ssl=1 666w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-serial-monitor-arduino-ide.png?resize=300%2C124&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 666px) 100vw, 666px\" \/><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"display-distance-oled\">Display Distance (HCSR04) on OLED Display (RPi Pico with Arduino IDE)<\/h2>\n\n\n\n<p>Now that you know how to get the distance to the closest object using an HC-SR04 ultrasonic sensor, we&#8217;ll display the sensor readings on an OLED display.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-display-on-oled.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico with Ultrasonic Sensor - Display Distance on OLED Display\" class=\"wp-image-171176\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-display-on-oled.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-display-on-oled.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgreen\">Recommended reading: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ssd1306-oled-arduino\/\">Raspberry Pi Pico: SSD1306 OLED Display (Arduino IDE)<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>Here&#8217;s a list of the parts required to complete this example:<\/p>\n\n\n\n<ul id=\"block-20d88f2a-6847-4e0b-a050-3bc5f026cbe4\" class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-pico-2-w\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi Pico<\/a> (any model)<\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">1kOhm resistor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/oled-display-128x64-0-96-inch\/\" target=\"_blank\" rel=\"noreferrer noopener\">0.96 inch I2C OLED Display SSD1306<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noreferrer noopener\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Schematic Diagram<\/h3>\n\n\n\n<p>Add an I2C OLED display to the previous circuit. We&#8217;re connecting SDA to <span class=\"rnthl rntcyellow\">GPIO 4<\/span>, and SCL to <span class=\"rnthl rntcgray\">GPIO 5<\/span>. You can follow the next schematic diagram:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"476\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-with-oled-wiring-diagram_bb.png?resize=1024%2C476&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico Ultrasonic Sensor and OLED Display - Wiring Diagram\" class=\"wp-image-170998\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-with-oled-wiring-diagram_bb.png?resize=1024%2C476&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-with-oled-wiring-diagram_bb.png?resize=300%2C139&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-with-oled-wiring-diagram_bb.png?resize=768%2C357&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-ultrasonic-sensor-with-oled-wiring-diagram_bb.png?w=1293&amp;quality=100&amp;strip=all&amp;ssl=1 1293w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Install the SSD1306 Library<\/h3>\n\n\n\n<p>In the Arduino IDE, go to <strong>Sketch<\/strong> &gt; <strong>Include Library<\/strong> &gt; <strong>Manage Libraries<\/strong>.<\/p>\n\n\n\n<p>Then, search for Adafruit SSD1306 and install the library.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"861\" height=\"586\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/01\/installing-oled-display-library-ssd1306.jpg?resize=861%2C586&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Installing OLED Library Arduino IDE\" class=\"wp-image-166448\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/01\/installing-oled-display-library-ssd1306.jpg?w=861&amp;quality=100&amp;strip=all&amp;ssl=1 861w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/01\/installing-oled-display-library-ssd1306.jpg?resize=300%2C204&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/01\/installing-oled-display-library-ssd1306.jpg?resize=768%2C523&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 861px) 100vw, 861px\" \/><\/figure><\/div>\n\n\n<p>Also, install any other required dependencies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Display the Distance On OLED Display<\/h3>\n\n\n\n<p>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.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n  Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-hc-sr04-arduino\/\n  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.\n  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*********\/\n\n#include &lt;Wire.h&gt;\n#include &lt;Adafruit_GFX.h&gt;\n#include &lt;Adafruit_SSD1306.h&gt;\n\n#define SCREEN_WIDTH 128 \/\/ OLED display width, in pixels\n#define SCREEN_HEIGHT 64 \/\/ OLED display height, in pixels\n\n\/\/ Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)\nAdafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, -1);\n\nconst int trigPin = 27;\nconst int echoPin = 28;\n\n\/\/define sound speed in cm\/uS\n#define SOUND_SPEED 0.034\n#define CM_TO_INCH 0.393701\n\nlong duration;\nint distanceCm;\nint distanceInch;\n\nvoid setup() {\n  Serial.begin(115200);\n  pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\n  pinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input\n\n  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {\n    Serial.println(F(&quot;SSD1306 allocation failed&quot;));\n    for(;;);\n  }\n  delay(500);\n  display.clearDisplay();\n\n  display.setTextSize(2);\n  display.setTextColor(WHITE);\n}\n\nvoid loop() {\n  \/\/ Clears the trigPin\n  digitalWrite(trigPin, LOW);\n  delayMicroseconds(2);\n  \/\/ Sets the trigPin on HIGH state for 10 micro seconds\n  digitalWrite(trigPin, HIGH);\n  delayMicroseconds(10);\n  digitalWrite(trigPin, LOW);\n  \n  \/\/ Reads the echoPin, returns the sound wave travel time in microseconds\n  duration = pulseIn(echoPin, HIGH);\n  \n  \/\/ Calculate the distance\n  distanceCm = duration * SOUND_SPEED\/2;\n  \n  \/\/ Convert to inches\n  distanceInch = distanceCm * CM_TO_INCH;\n  \n  \/\/ Prints the distance in the Serial Monitor\n  Serial.print(&quot;Distance (cm): &quot;);\n  Serial.println(distanceCm);\n  Serial.print(&quot;Distance (inch): &quot;);\n  Serial.println(distanceInch);\n\n  display.clearDisplay();\n  display.setCursor(0, 25);\n  \/\/Display distance in cm\n  display.print(distanceCm);\n  display.print(&quot; cm&quot;);\n  \n  \/\/ Display distance in inches\n  \/* display.print(distanceInch);\n  display.print(&quot; in&quot;);*\/\n  display.display(); \n\n  delay(500);  \n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi-Pico\/Arduino\/HC_SR04_Ultrasonic_OLED.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Start by including the required libraries for the OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;Wire.h&gt;\n#include &lt;Adafruit_GFX.h&gt;\n#include &lt;Adafruit_SSD1306.h&gt;<\/code><\/pre>\n\n\n\n<p>Define the width and height of the OLED display. We&#8217;re using a 128&#215;64 OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define SCREEN_WIDTH 128 \/\/ OLED display width, in pixels\n#define SCREEN_HEIGHT 64 \/\/ OLED display height, in pixels<\/code><\/pre>\n\n\n\n<p>Create an <span class=\"rnthl rntliteral\">Adafruit_SSD1306<\/span> object called <span class=\"rnthl rntliteral\">display<\/span> to handle the OLED display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &amp;Wire);<\/code><\/pre>\n\n\n\n<p>Define the pins that the HC-SR04 sensor is connected to.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const int trigPin = 27;\nconst int echoPin = 28;<\/code><\/pre>\n\n\n\n<p>Create variables to save the distance and the duration between the transmission and reception of the sound waves.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>long duration;\nint distanceCm;\nint distanceInch;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">setup()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, initialize a serial communication at a baud rate of 115200 so that we can print the results on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>Define the trigger pin as an <span class=\"rnthl rntliteral\">OUTPUT<\/span> and the echo pin as an <span class=\"rnthl rntliteral\">INPUT<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\npinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input<\/code><\/pre>\n\n\n\n<p>Initialize the OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {\n  Serial.println(F(\"SSD1306 allocation failed\"));\n  for(;;);\n}<\/code><\/pre>\n\n\n\n<p>Set the font size and color for the display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.setTextSize(2);\ndisplay.setTextColor(WHITE);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">loop()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span> is where we&#8217;ll get the distance and display it on the OLED.<\/p>\n\n\n\n<p>Get the distance (we&#8217;ve already explained in the previous section how to calculate the distance).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Clears the trigPin\ndigitalWrite(trigPin, LOW);\ndelayMicroseconds(2);\n\/\/ Sets the trigPin on HIGH state for 10 micro seconds\ndigitalWrite(trigPin, HIGH);\ndelayMicroseconds(10);\ndigitalWrite(trigPin, LOW);\n  \n\/\/ Reads the echoPin, returns the sound wave travel time in microseconds\nduration = pulseIn(echoPin, HIGH);\n  \n\/\/ Calculate the distance\ndistanceCm = duration * SOUND_SPEED\/2;\n  \n\/\/ Convert to inches\ndistanceInch = distanceCm * CM_TO_INCH;<\/code><\/pre>\n\n\n\n<p>Print the distance on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Prints the distance on the Serial Monitor\nSerial.print(\"Distance (cm): \");\nSerial.println(distanceCm);\nSerial.print(\"Distance (inch): \");\nSerial.println(distanceInch);<\/code><\/pre>\n\n\n\n<p>Clear the display in each <span class=\"rnthl rntliteral\">loop()<\/span> to write new readings.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.clearDisplay();<\/code><\/pre>\n\n\n\n<p>Set the display cursor to (0, 25).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.setCursor(0, 25);<\/code><\/pre>\n\n\n\n<p>The following lines print the distance in centimeters in the OLED display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Display static text\ndisplay.print(distanceCm);\ndisplay.print(\" cm\");<\/code><\/pre>\n\n\n\n<p>Comment the previous lines and uncomment the following lines if you want to display the readings in inches.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/* Display distance in inches\ndisplay.print(distanceInch);\ndisplay.print(\" in\");*\/<\/code><\/pre>\n\n\n\n<p>Lastly, call <span class=\"rnthl rntliteral\">display.display()<\/span> to actually show the readings on the OLED.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.display();<\/code><\/pre>\n\n\n\n<p>The distance is updated every 500 milliseconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>delay(500);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Demonstration<\/h3>\n\n\n\n<p>Upload the code to the Raspberry Pi Pico.<\/p>\n\n\n\n<p>The distance to the closest object will be printed on the OLED screen.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-ultrasonic-sensor-display-distance-on-display-1.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico with Ultrasonic Sensor - Display Distance on OLED Display\" class=\"wp-image-171177\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-ultrasonic-sensor-display-distance-on-display-1.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-ultrasonic-sensor-display-distance-on-display-1.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>The HC-SR04 Ultrasonic Sensor allows us to determine the distance to an object. In this tutorial, you&#8217;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:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-anemometer-arduino\/\">Raspberry Pi Pico with <strong>Anemometer<\/strong>: Measure Wind Speed (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme680-arduino\/\">Raspberry Pi Pico: <strong>BME680<\/strong> Environmental Sensor (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-motion-pir-arduino\/\">Raspberry Pi Pico: Detect Motion using a <strong>PIR Sensor<\/strong> (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme280-arduino\/\">Raspberry Pi Pico: <strong>BME280<\/strong> Get Temperature, Humidity, and Pressure (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-rcwl-0516-arduino\/\">Raspberry Pi Pico: RCWL-0516 <strong>Microwave Radar Proximity Sensor<\/strong> (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ssd1306-oled-arduino\/\">Raspberry Pi Pico: <strong>SSD1306 OLED Display<\/strong> (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-guides-sensors-modules\/\">Raspberry Pi Pico: 20+ Free Guides for Sensors and Modules<\/a><\/li>\n<\/ul>\n\n\n\n<p>You can check <a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\" title=\"\"><strong>all our Raspberry Pi Pico tutorials and guides here<\/strong><\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (Arduino IDE)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-hc-sr04-arduino\/#more-171169\" aria-label=\"Read more about Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (Arduino IDE)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":171186,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[324,325],"tags":[],"class_list":["post-171169","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-arduino-ide"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Arduino-ide.jpg?fit=1920%2C1080&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/171169","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=171169"}],"version-history":[{"count":7,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/171169\/revisions"}],"predecessor-version":[{"id":176218,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/171169\/revisions\/176218"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/171186"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=171169"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=171169"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=171169"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}