{"id":170969,"date":"2025-08-28T13:15:07","date_gmt":"2025-08-28T13:15:07","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=170969"},"modified":"2026-01-22T19:31:32","modified_gmt":"2026-01-22T19:31:32","slug":"raspberry-pi-pico-hc-sr04-micropython","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-hc-sr04-micropython\/","title":{"rendered":"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (MicroPython)"},"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 using MicroPython firmware. This tutorial covers how to wire the sensor to the board and provides a simple MicroPython script for measuring the distance to an object and displaying it on an OLED display.<\/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-Micropython-tutorial.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor - Measure Distance (MicroPython)\" class=\"wp-image-170999\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Micropython-tutorial.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-Micropython-tutorial.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-Micropython-tutorial.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-Micropython-tutorial.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-Micropython-tutorial.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\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\">Check out our eBook: Learn Raspberry Pi Pico\/Pico W with MicroPython<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents<\/strong>:<\/p>\n\n\n\n<p>In this guide, we&#8217;ll cover the following topics:<\/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=\"#micropython-library-ultrasonic-sensor\" title=\"\">HC-SR04 MicroPython Library<\/a><\/li>\n\n\n\n<li><a href=\"#ultrasonic-sensor-with-rpi-pico-basic-code\" title=\"\">Code &#8211; HC-SR04 Ultrasonic Sensor with the RPi Pico<\/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=\"prerequisites\">Prerequisites \u2013 MicroPython Firmware<\/h2>\n\n\n\n<p>To follow this tutorial, you need MicroPython firmware installed on your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.<\/p>\n\n\n\n<p>The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/#install-thonny-ide\">Programming Raspberry Pi Pico using MicroPython<\/a><\/li>\n<\/ul>\n\n\n\n<p>If you&#8217;re still getting started with the Raspberry Pi Pico, follow one of these getting-started guides:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-2-w\/\">Getting Started with Raspberry Pi Pico 2 and Pico 2 W<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-raspberry-pi-pico-w\/\">Getting Started with Raspberry Pi Pico (and Pico W)<\/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-micropython\/\">Raspberry Pi Pico: RCWL-0516 Microwave Radar Proximity Sensor (MicroPython)<\/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=\"micropython-library-ultrasonic-sensor\">HC-SR04 MicroPython Library<\/h2>\n\n\n\n<p>There are multiple ways to get the distance to an object using the HC-SR04 and RPi Pico board using MicroPython firmware. We&#8217;ll use this <a href=\"https:\/\/github.com\/rsc1975\/micropython-hcsr04\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 MicroPython Library<\/a> that makes it straightforward to interface the sensor and get measurements.<\/p>\n\n\n\n<p>The library we&#8217;ll use isn\u2019t part of the standard MicroPython library by default. So, you need to upload the following library to your RPi Pico board (save it with the name <em><span class=\"rnthl rntliteral\"><strong>hcsr04.py<\/strong><\/span><\/em>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\">import machine, time\r\nfrom machine import Pin\r\n\r\n__version__ = '0.2.0'\r\n__author__ = 'Roberto S\u00e1nchez'\r\n__license__ = &quot;Apache License 2.0. https:\/\/www.apache.org\/licenses\/LICENSE-2.0&quot;\r\n\r\nclass HCSR04:\r\n    &quot;&quot;&quot;\r\n    Driver to use the untrasonic sensor HC-SR04.\r\n    The sensor range is between 2cm and 4m.\r\n    The timeouts received listening to echo pin are converted to OSError('Out of range')\r\n    &quot;&quot;&quot;\r\n    # echo_timeout_us is based in chip range limit (400cm)\r\n    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):\r\n        &quot;&quot;&quot;\r\n        trigger_pin: Output pin to send pulses\r\n        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor\r\n        echo_timeout_us: Timeout in microseconds to listen to echo pin. \r\n        By default is based in sensor limit range (4m)\r\n        &quot;&quot;&quot;\r\n        self.echo_timeout_us = echo_timeout_us\r\n        # Init trigger pin (out)\r\n        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)\r\n        self.trigger.value(0)\r\n\r\n        # Init echo pin (in)\r\n        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)\r\n\r\n    def _send_pulse_and_wait(self):\r\n        &quot;&quot;&quot;\r\n        Send the pulse to trigger and listen on echo pin.\r\n        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.\r\n        &quot;&quot;&quot;\r\n        self.trigger.value(0) # Stabilize the sensor\r\n        time.sleep_us(5)\r\n        self.trigger.value(1)\r\n        # Send a 10us pulse.\r\n        time.sleep_us(10)\r\n        self.trigger.value(0)\r\n        try:\r\n            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)\r\n            return pulse_time\r\n        except OSError as ex:\r\n            if ex.args[0] == 110: # 110 = ETIMEDOUT\r\n                raise OSError('Out of range')\r\n            raise ex\r\n\r\n    def distance_mm(self):\r\n        &quot;&quot;&quot;\r\n        Get the distance in milimeters without floating point operations.\r\n        &quot;&quot;&quot;\r\n        pulse_time = self._send_pulse_and_wait()\r\n\r\n        # To calculate the distance we get the pulse_time and divide it by 2 \r\n        # (the pulse walk the distance twice) and by 29.1 becasue\r\n        # the sound speed on air (343.2 m\/s), that It's equivalent to\r\n        # 0.34320 mm\/us that is 1mm each 2.91us\r\n        # pulse_time \/\/ 2 \/\/ 2.91 -&gt; pulse_time \/\/ 5.82 -&gt; pulse_time * 100 \/\/ 582 \r\n        mm = pulse_time * 100 \/\/ 582\r\n        return mm\r\n\r\n    def distance_cm(self):\r\n        &quot;&quot;&quot;\r\n        Get the distance in centimeters with floating point operations.\r\n        It returns a float\r\n        &quot;&quot;&quot;\r\n        pulse_time = self._send_pulse_and_wait()\r\n\r\n        # To calculate the distance we get the pulse_time and divide it by 2 \r\n        # (the pulse walk the distance twice) and by 29.1 becasue\r\n        # the sound speed on air (343.2 m\/s), that It's equivalent to\r\n        # 0.034320 cm\/us that is 1cm each 29.1us\r\n        cms = (pulse_time \/ 2) \/ 29.1\r\n        return cms<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/HCSR04\/hcsr04.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Upload HC-SR04 module to the RPi Pico<\/h3>\n\n\n\n<p>Follow the next steps to upload the <span class=\"rnthl rntliteral\"><em>hcsr04.py<\/em><\/span> file to your board.<\/p>\n\n\n\n<p><strong>1.<\/strong>&nbsp;Copy the library code to a new file. The&nbsp;HC-SR04 library code can be found <a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/master\/Projects\/ESP-MicroPython\/HCSR04\/hcsr04.py\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n\n\n\n<p><strong>2.<\/strong>&nbsp;Go to&nbsp;<strong>File<\/strong>&nbsp;&gt;&nbsp;<strong>Save as\u2026<\/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=\"206\" height=\"294\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/Thonny-IDE-ESP32-ESP8266-MicroPython-Save-file-library-to-device-save-as.png?resize=206%2C294&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE ESP32 ESP8266 MicroPython Save file library to device save as\" class=\"wp-image-99603\"\/><\/figure><\/div>\n\n\n<p><strong>3.<\/strong>&nbsp;Select save to \u201c<strong>Raspberry Pi Pico<\/strong>\u201c:<\/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=\"214\" height=\"203\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/05\/Save-file-to-Raspberry-Pi-Pico.png?resize=214%2C203&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Save Files to Raspberry Pi Pico Thonny IDE\" class=\"wp-image-130899\"\/><\/figure><\/div>\n\n\n<p><strong>4.<\/strong>&nbsp;Name your file as&nbsp;<em>hcsr04.py<\/em>&nbsp;and press the OK button:<\/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=\"545\" height=\"327\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-save-to-rpi-pico-f.png?resize=545%2C327&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HCSR04-save-file-to-rpi-pico\" class=\"wp-image-170975\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-save-to-rpi-pico-f.png?w=545&amp;quality=100&amp;strip=all&amp;ssl=1 545w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-save-to-rpi-pico-f.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 545px) 100vw, 545px\" \/><\/figure><\/div>\n\n\n<p>And that\u2019s it. The library was uploaded to your board. To make sure that it was uploaded successfully, go to <strong>File <\/strong>&gt; <strong>Save as\u2026<\/strong> and select the Raspberry Pi Pico device. Your file should be listed there:<\/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=\"545\" height=\"327\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-saved-to-rpi-pico.png?resize=545%2C327&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR04 library MicroPython file created Thonny IDE\" class=\"wp-image-170973\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-saved-to-rpi-pico.png?w=545&amp;quality=100&amp;strip=all&amp;ssl=1 545w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/hcsr04-file-saved-to-rpi-pico.png?resize=300%2C180&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 545px) 100vw, 545px\" \/><\/figure><\/div>\n\n\n<p>After uploading the library to your board, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ultrasonic-sensor-with-rpi-pico-basic-code\">Code &#8211; HC-SR04 Ultrasonic Sensor with the RPi Pico<\/h2>\n\n\n\n<p>After uploading the library to the RPi Pico board, copy the following code to Thonny IDE. It simply prints the distance to the closest object every second (example adapted from the <a href=\"https:\/\/github.com\/rsc1975\/micropython-hcsr04\" target=\"_blank\" rel=\"noopener\" title=\"\">library page<\/a>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-hc-sr04-micropython\/\n\nfrom machine import Pin\nimport time\nfrom hcsr04 import HCSR04\n\n# Initialize the HC-SR04 sensor with trigger on GPIO 27 and echo on GPIO 28\nsensor = HCSR04(trigger_pin=27, echo_pin=28, echo_timeout_us=30000)\n\nwhile True:\n    try:\n        # Measure distance in centimeters\n        #distance_cm = sensor.distance_cm()\n        # Convert distance from centimeters to inches\n        #distance_inch = distance_cm * 0.393701\n        #print('Distance: {:.2f} cm'.format(distance_cm))\n        \n        # Measure distance in millimeters\n        distance_mm = sensor.distance_mm()\n        print('Distance: {} mm'.format(distance_mm))\n\n    except OSError as e:\n        print('Error:', e)\n    \n    # Wait 1 second before the next measurement\n    time.sleep(1) \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\/MicroPython\/HC_SR04_Basic.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>First, you need to import the necessary libraries: import the <span class=\"rnthl rntliteral\">HCSR04<\/span> class from the <span class=\"rnthl rntliteral\">hcsr04<\/span> library. Additionally, you also need to import the <span class=\"rnthl rntliteral\">time<\/span> library to add delays to our code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from hcsr04 import HCSR04\nfrom time import sleep<\/code><\/pre>\n\n\n\n<p>Then, create an <span class=\"rnthl rntliteral\">HCSR04<\/span> object called <span class=\"rnthl rntliteral\">sensor<\/span> that refers to the HCSR04 sensor. Pass as arguments the trigger pin, the echo pin, and the timeout (maximum travel time of the sound wave\u2014when the sensor is probably out of range).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = HCSR04(trigger_pin=27, echo_pin=28, echo_timeout_us=30000)<\/code><\/pre>\n\n\n\n<p>To get the distance in cm, you just need to call the <span class=\"rnthl rntliteral\">distance_cm<\/span> method on the <span class=\"rnthl rntliteral\">sensor<\/span> object. Save the result in the <span class=\"rnthl rntliteral\">distance_cm<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>distance_cm = sensor.distance_cm()<\/code><\/pre>\n\n\n\n<p>The library also provides a method to get the distance in millimeters without floating point. You just need to call:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>distance_mm = sensor.distance_mm()<\/code><\/pre>\n\n\n\n<p>Print the distance on the Micropython shell.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>print('Distance: {} mm'.format(distance_mm))<\/code><\/pre>\n\n\n\n<p>In the end, we add a delay of one second (the distance is updated every second):<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sleep(1)<\/code><\/pre>\n\n\n\n<p>We get the distance inside <span class=\"rnthl rntliteral\">try<\/span> and <span class=\"rnthl rntliteral\">except<\/span> statements, so that the code doesn&#8217;t get stuck if we get an error.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    # Measure distance in centimeters\n    #distance_cm = sensor.distance_cm()\n    #print('Distance: {:.2f} cm'.format(distance_cm))\n        \n    # Measure distance in millimeters\n    distance_mm = sensor.distance_mm()\n    print('Distance: {} mm'.format(distance_mm))\n\nexcept OSError as e:\n    print('Error:', e)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>After uploading the code to your board, press the RST button to run 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=\"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 should be printed on the shell.<\/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=\"678\" height=\"315\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-micropython-shell.jpg?resize=678%2C315&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Pico with HC-SR04 MicroPython Demonstration on the Shell\" class=\"wp-image-170978\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-micropython-shell.jpg?w=678&amp;quality=100&amp;strip=all&amp;ssl=1 678w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-hcsr04-get-distance-micropython-shell.jpg?resize=300%2C139&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 678px) 100vw, 678px\" \/><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-css-opacity is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"display-distance-oled\">Display Distance (HCSR04) on OLED Display<\/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-Display-Distance-on-OLED-display.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"RPi Pico with HCSR04 - display distance on OLED display\" class=\"wp-image-170991\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-HCSR04-Display-Distance-on-OLED-display.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-Display-Distance-on-OLED-display.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\">Parts Required<\/h2>\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=\"\">1k Ohm 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<h2 class=\"wp-block-heading\">Schematic Diagram<\/h2>\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<h2 class=\"wp-block-heading\">Files<\/h2>\n\n\n\n<p>For this example, you need three files:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>hcsr04.py<\/em><\/strong>: this is the file that contains all the methods to use the HC-SR04 sensor. That&#8217;s the file you&#8217;ve uploaded previously.<\/li>\n\n\n\n<li><strong>ssd1306.py<\/strong>: this is the library for the SSD1306 I2C OLED display. You should upload it to your board to be able to communicate and write on the display.<\/li>\n\n\n\n<li><strong><em>main.py<\/em><\/strong>: this is the main script to get the distance and display it on the OLED display. You should call it main.py and upload it to your board. When you upload a code called <span class=\"rnthl rntliteral\">main.py<\/span> to the RPi Pico filesystem, that file will automatically run when the RPi Pico starts.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">ssd1306.py<\/h3>\n\n\n\n<p>Create a new file on Thonny IDE called <em>ssd1306.py<\/em> and copy the following code. Then, upload it to your board (<strong>File &gt; Save as&#8230; &gt; MicroPython device<\/strong> and call it <span class=\"rnthl rntliteral\"><em><strong>ssd1306.py<\/strong><\/em><\/span>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># MicroPython SSD1306 OLED driver, I2C and SPI interfaces created by Adafruit\n\nimport time\nimport framebuf\n\n# register definitions\nSET_CONTRAST        = const(0x81)\nSET_ENTIRE_ON       = const(0xa4)\nSET_NORM_INV        = const(0xa6)\nSET_DISP            = const(0xae)\nSET_MEM_ADDR        = const(0x20)\nSET_COL_ADDR        = const(0x21)\nSET_PAGE_ADDR       = const(0x22)\nSET_DISP_START_LINE = const(0x40)\nSET_SEG_REMAP       = const(0xa0)\nSET_MUX_RATIO       = const(0xa8)\nSET_COM_OUT_DIR     = const(0xc0)\nSET_DISP_OFFSET     = const(0xd3)\nSET_COM_PIN_CFG     = const(0xda)\nSET_DISP_CLK_DIV    = const(0xd5)\nSET_PRECHARGE       = const(0xd9)\nSET_VCOM_DESEL      = const(0xdb)\nSET_CHARGE_PUMP     = const(0x8d)\n\n\nclass SSD1306:\n    def __init__(self, width, height, external_vcc):\n        self.width = width\n        self.height = height\n        self.external_vcc = external_vcc\n        self.pages = self.height \/\/ 8\n        # Note the subclass must initialize self.framebuf to a framebuffer.\n        # This is necessary because the underlying data buffer is different\n        # between I2C and SPI implementations (I2C needs an extra byte).\n        self.poweron()\n        self.init_display()\n\n    def init_display(self):\n        for cmd in (\n            SET_DISP | 0x00, # off\n            # address setting\n            SET_MEM_ADDR, 0x00, # horizontal\n            # resolution and layout\n            SET_DISP_START_LINE | 0x00,\n            SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0\n            SET_MUX_RATIO, self.height - 1,\n            SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0\n            SET_DISP_OFFSET, 0x00,\n            SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,\n            # timing and driving scheme\n            SET_DISP_CLK_DIV, 0x80,\n            SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,\n            SET_VCOM_DESEL, 0x30, # 0.83*Vcc\n            # display\n            SET_CONTRAST, 0xff, # maximum\n            SET_ENTIRE_ON, # output follows RAM contents\n            SET_NORM_INV, # not inverted\n            # charge pump\n            SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,\n            SET_DISP | 0x01): # on\n            self.write_cmd(cmd)\n        self.fill(0)\n        self.show()\n\n    def poweroff(self):\n        self.write_cmd(SET_DISP | 0x00)\n\n    def contrast(self, contrast):\n        self.write_cmd(SET_CONTRAST)\n        self.write_cmd(contrast)\n\n    def invert(self, invert):\n        self.write_cmd(SET_NORM_INV | (invert &amp; 1))\n\n    def show(self):\n        x0 = 0\n        x1 = self.width - 1\n        if self.width == 64:\n            # displays with width of 64 pixels are shifted by 32\n            x0 += 32\n            x1 += 32\n        self.write_cmd(SET_COL_ADDR)\n        self.write_cmd(x0)\n        self.write_cmd(x1)\n        self.write_cmd(SET_PAGE_ADDR)\n        self.write_cmd(0)\n        self.write_cmd(self.pages - 1)\n        self.write_framebuf()\n\n    def fill(self, col):\n        self.framebuf.fill(col)\n\n    def pixel(self, x, y, col):\n        self.framebuf.pixel(x, y, col)\n\n    def scroll(self, dx, dy):\n        self.framebuf.scroll(dx, dy)\n\n    def text(self, string, x, y, col=1):\n        self.framebuf.text(string, x, y, col)\n\n\nclass SSD1306_I2C(SSD1306):\n    def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):\n        self.i2c = i2c\n        self.addr = addr\n        self.temp = bytearray(2)\n        # Add an extra byte to the data buffer to hold an I2C data\/command byte\n        # to use hardware-compatible I2C transactions.  A memoryview of the\n        # buffer is used to mask this byte from the framebuffer operations\n        # (without a major memory hit as memoryview doesn't copy to a separate\n        # buffer).\n        self.buffer = bytearray(((height \/\/ 8) * width) + 1)\n        self.buffer[0] = 0x40  # Set first byte of data buffer to Co=0, D\/C=1\n        self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)\n        super().__init__(width, height, external_vcc)\n\n    def write_cmd(self, cmd):\n        self.temp[0] = 0x80 # Co=1, D\/C#=0\n        self.temp[1] = cmd\n        self.i2c.writeto(self.addr, self.temp)\n\n    def write_framebuf(self):\n        # Blast out the frame buffer using a single I2C transaction to support\n        # hardware I2C interfaces.\n        self.i2c.writeto(self.addr, self.buffer)\n\n    def poweron(self):\n        pass\n\n\nclass SSD1306_SPI(SSD1306):\n    def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):\n        self.rate = 10 * 1024 * 1024\n        dc.init(dc.OUT, value=0)\n        res.init(res.OUT, value=0)\n        cs.init(cs.OUT, value=1)\n        self.spi = spi\n        self.dc = dc\n        self.res = res\n        self.cs = cs\n        self.buffer = bytearray((height \/\/ 8) * width)\n        self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)\n        super().__init__(width, height, external_vcc)\n\n    def write_cmd(self, cmd):\n        self.spi.init(baudrate=self.rate, polarity=0, phase=0)\n        self.cs.high()\n        self.dc.low()\n        self.cs.low()\n        self.spi.write(bytearray([cmd]))\n        self.cs.high()\n\n    def write_framebuf(self):\n        self.spi.init(baudrate=self.rate, polarity=0, phase=0)\n        self.cs.high()\n        self.dc.high()\n        self.cs.low()\n        self.spi.write(self.buffer)\n        self.cs.high()\n\n    def poweron(self):\n        self.res.high()\n        time.sleep_ms(1)\n        self.res.low()\n        time.sleep_ms(10)\n        self.res.high()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/ESP-MicroPython\/raw\/master\/code\/Others\/OLED\/ssd1306.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">hcsr04.py<\/h3>\n\n\n\n<p>Upload the <em>hcsr04.py<\/em> to your board if you haven&#8217;t already (<strong>File &gt; Save as&#8230; &gt; MicroPython device<\/strong> and call it <span class=\"rnthl rntliteral\"><em><strong>hcsr04.py<\/strong><\/em><\/span>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\">import machine, time\r\nfrom machine import Pin\r\n\r\n__version__ = '0.2.0'\r\n__author__ = 'Roberto S\u00e1nchez'\r\n__license__ = &quot;Apache License 2.0. https:\/\/www.apache.org\/licenses\/LICENSE-2.0&quot;\r\n\r\nclass HCSR04:\r\n    &quot;&quot;&quot;\r\n    Driver to use the untrasonic sensor HC-SR04.\r\n    The sensor range is between 2cm and 4m.\r\n    The timeouts received listening to echo pin are converted to OSError('Out of range')\r\n    &quot;&quot;&quot;\r\n    # echo_timeout_us is based in chip range limit (400cm)\r\n    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):\r\n        &quot;&quot;&quot;\r\n        trigger_pin: Output pin to send pulses\r\n        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor\r\n        echo_timeout_us: Timeout in microseconds to listen to echo pin. \r\n        By default is based in sensor limit range (4m)\r\n        &quot;&quot;&quot;\r\n        self.echo_timeout_us = echo_timeout_us\r\n        # Init trigger pin (out)\r\n        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)\r\n        self.trigger.value(0)\r\n\r\n        # Init echo pin (in)\r\n        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)\r\n\r\n    def _send_pulse_and_wait(self):\r\n        &quot;&quot;&quot;\r\n        Send the pulse to trigger and listen on echo pin.\r\n        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.\r\n        &quot;&quot;&quot;\r\n        self.trigger.value(0) # Stabilize the sensor\r\n        time.sleep_us(5)\r\n        self.trigger.value(1)\r\n        # Send a 10us pulse.\r\n        time.sleep_us(10)\r\n        self.trigger.value(0)\r\n        try:\r\n            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)\r\n            return pulse_time\r\n        except OSError as ex:\r\n            if ex.args[0] == 110: # 110 = ETIMEDOUT\r\n                raise OSError('Out of range')\r\n            raise ex\r\n\r\n    def distance_mm(self):\r\n        &quot;&quot;&quot;\r\n        Get the distance in milimeters without floating point operations.\r\n        &quot;&quot;&quot;\r\n        pulse_time = self._send_pulse_and_wait()\r\n\r\n        # To calculate the distance we get the pulse_time and divide it by 2 \r\n        # (the pulse walk the distance twice) and by 29.1 becasue\r\n        # the sound speed on air (343.2 m\/s), that It's equivalent to\r\n        # 0.34320 mm\/us that is 1mm each 2.91us\r\n        # pulse_time \/\/ 2 \/\/ 2.91 -&gt; pulse_time \/\/ 5.82 -&gt; pulse_time * 100 \/\/ 582 \r\n        mm = pulse_time * 100 \/\/ 582\r\n        return mm\r\n\r\n    def distance_cm(self):\r\n        &quot;&quot;&quot;\r\n        Get the distance in centimeters with floating point operations.\r\n        It returns a float\r\n        &quot;&quot;&quot;\r\n        pulse_time = self._send_pulse_and_wait()\r\n\r\n        # To calculate the distance we get the pulse_time and divide it by 2 \r\n        # (the pulse walk the distance twice) and by 29.1 becasue\r\n        # the sound speed on air (343.2 m\/s), that It's equivalent to\r\n        # 0.034320 cm\/us that is 1cm each 29.1us\r\n        cms = (pulse_time \/ 2) \/ 29.1\r\n        return cms<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/HCSR04\/hcsr04.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">main.py<\/h3>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\"><em>main.py<\/em><\/span> file is where we&#8217;ll get the distance and display it on the OLED display. Upload it to your board with the name <span class=\"rnthl rntliteral\"><em>main.py<\/em><\/span>.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n# Complete project details at https:\/\/RandomNerdTutorials.com\/raspberry-pi-pico-hc-sr04-micropython\/\n\nfrom machine import Pin, I2C\nimport ssd1306\nfrom hcsr04 import HCSR04\nfrom time import sleep\n\n# Initialize I2C for SSD1306 OLED (Pico: SCL = GPIO 5, SDA = GPIO 4 for I2C1)\ni2c = I2C(scl=Pin(5), sda=Pin(4))\n\n# Initialize HC-SR04 ultrasonic sensor (trigger = GPIO 27, echo = GPIO 28)\nsensor = HCSR04(trigger_pin=27, echo_pin=28, echo_timeout_us=10000)\n\n# Initialize SSD1306 OLED (128x64)\noled_width = 128\noled_height = 64\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)\n\nwhile True:\n    try:\n        # Measure distance in centimeters\n        distance_cm = sensor.distance_cm()\n        # Convert distance from centimeters to inches\n        #distance_inch = distance_cm * 0.393701\n        \n        # Print to shell\n        print('Distance: {:.2f} cm'.format(distance_cm))\n        \n        # Clear OLED and display distance in cm\n        oled.fill(0)\n        oled.text(&quot;Distance:&quot;, 0, 10)\n        oled.text(&quot;{:.2f} cm&quot;.format(distance_cm), 0, 30)\n        oled.show()\n        \n    except OSError as e:\n        # Handle sensor errors (e.g., out of range)\n        print('Error:', e)\n        oled.fill(0)\n        oled.text(&quot;Error:&quot;, 0, 10)\n        oled.text(&quot;Out of range&quot;, 0, 30)\n        oled.show()\n    \n    # Wait 1 second before next measurement\n    sleep(1)\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\/MicroPython\/HC_SR04_OLED.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>The code is straightforward to understand. To learn more about using the OLED display with the RPi Pico using MicroPython, refer to the next tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ssd1306-oled-micropython\/\" title=\"\">Raspberry Pi Pico: SSD1306 OLED Display (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p>The code starts by importing the required libraries.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from machine import Pin, I2C\nimport ssd1306\nfrom hcsr04 import HCSR04\nfrom time import sleep<\/code><\/pre>\n\n\n\n<p>Set the pins for the OLED display and ultrasonic sensor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>i2c = I2C(scl=Pin(5), sda=Pin(4))\nsensor = HCSR04(trigger_pin=27, echo_pin=28, echo_timeout_us=10000)<\/code><\/pre>\n\n\n\n<p>Define the OLED width and height and initialize the OLED display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>oled_width = 128\noled_height = 64\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">while<\/span> loop is where we&#8217;ll get the distance and display it on the OLED. Like in the previous code, we use <span class=\"rnthl rntliteral\">try<\/span> and <span class=\"rnthl rntliteral\">except<\/span> statements to catch any errors that might occur during the execution of the program.<\/p>\n\n\n\n<p>Get the distance in cm and save it in the <span class=\"rnthl rntliteral\">distance_cm<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>distance = sensor.distance_cm()<\/code><\/pre>\n\n\n\n<p>Print the distance in the console.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>print('Distance:', distance, 'mm')<\/code><\/pre>\n\n\n\n<p>Clear the display in each iteration with <span class=\"rnthl rntliteral\">oled.fill(0)<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>oled.fill(0)<\/code><\/pre>\n\n\n\n<p>Display the distance in the display. <\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>oled.fill(0)\noled.text(\"Distance:\", 0, 10)\noled.text(\"{:.2f} cm\".format(distance_cm), 0, 30)\noled.show()<\/code><\/pre>\n\n\n\n<p>Finally, call <span class=\"rnthl rntliteral\">oled.show()<\/span> to actually display the text.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>oled.show()<\/code><\/pre>\n\n\n\n<p>The distance is updated every second.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sleep(1)<\/code><\/pre>\n\n\n\n<p>In case there are any errors, they will be handled in the <span class=\"rnthl rntliteral\">except<\/span> statement.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except OSError as e:\n    # Handle sensor errors\n    print('Error:', e)\n    oled.fill(0)\n    oled.text(\"Error:\", 0, 10)\n    oled.text(\"Out of range\", 0, 30)\n    oled.show()    <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Upload all the previous files to your RPi Pico board in the following order as explained previously:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><em>ssd1306.py<\/em><\/li>\n\n\n\n<li><em>hcsr04.py<\/em><\/li>\n\n\n\n<li><em>main.py<\/em><\/li>\n<\/ol>\n\n\n\n<p>After uploading the code, it should start running, and it will display the distance in mm on the OLED display, as shown in the following picture.<\/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=\"460\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-ultrasonic-sensor-display-distance-on-display.jpg?resize=750%2C460&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython Raspberry Pi Pico with HC-SR04 Ultrasonic Sensor Module with OLED display\" class=\"wp-image-170992\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/RPi-Pico-with-ultrasonic-sensor-display-distance-on-display.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.jpg?resize=300%2C184&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>We hope you&#8217;ve found this tutorial useful. We have more projects and tutorials for the Raspberry Pi Pico with MicroPython with other popular sensors that you may like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-ds3231-rtc-micropython\/\">Raspberry Pi Pico:<strong> DS3231 RTC (Real-Time Clock)<\/strong> \u2013 Get Time and Set Alarms (MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-bme680-micropython\/\">Raspberry Pi Pico: <strong>BME680 Environmental Sensor <\/strong>(MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-motion-pir-micropython\/\">Raspberry Pi Pico: Detect Motion using a <strong>PIR Sensor <\/strong>(MicroPython)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-rcwl-0516-micropython\/\">Raspberry Pi Pico: <strong>RCWL-0516 Microwave Radar Proximity Sensor<\/strong> (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p>You can check<strong> <a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi-pico\/\" title=\"\">all our Raspberry Pi Pico projects and tutorials here<\/a><\/strong>.<\/p>\n\n\n\n<p>If you want to learn more about the Raspberry Pi Pico and MicroPython, check out our eBook: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-w-micropython-ebook\/\" title=\"\"><strong>Learn Raspberry Pi Pico\/Pico W with MicroPython<\/strong><\/a> (compatible with RPi Pico version 1 and 2). <\/p>\n\n\n\n<p>Thanks for reading.<\/p>\n\n\n\n<p><\/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 using MicroPython firmware. This tutorial covers how to wire the &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (MicroPython)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-hc-sr04-micropython\/#more-170969\" aria-label=\"Read more about Raspberry Pi Pico: HC-SR04 Ultrasonic Sensor (MicroPython)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":170999,"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,326],"tags":[],"class_list":["post-170969","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-raspberry-pi-pico","category-raspberry-pi-pico-micropython"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2025\/06\/Raspberry-Pi-Pico-Ultrasonic-Sensor-Micropython-tutorial.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\/170969","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=170969"}],"version-history":[{"count":14,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/170969\/revisions"}],"predecessor-version":[{"id":187704,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/170969\/revisions\/187704"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/170999"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=170969"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=170969"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=170969"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}