{"id":104589,"date":"2021-08-19T14:21:09","date_gmt":"2021-08-19T14:21:09","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=104589"},"modified":"2021-09-03T09:42:56","modified_gmt":"2021-09-03T09:42:56","slug":"micropython-hc-sr04-ultrasonic-esp32-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/micropython-hc-sr04-ultrasonic-esp32-esp8266\/","title":{"rendered":"MicroPython: HC-SR04 Ultrasonic Sensor with ESP32 and ESP8266 (Measure distance)"},"content":{"rendered":"\n<p>In this guide, you&#8217;ll learn how to use the HC-SR04 Ultrasonic Sensor with the ESP32 and ESP8266 to get the distance to an object using MicroPython firmware. This tutorial covers how to wire the sensor to the ESP32 and ESP8266 boards and provides a simple MicroPython script to get the distance to an object and display it on an OLED display.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?resize=1024%2C576&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython HC-SR04 Ultrasonic Sensor with ESP32 ESP8266 NodeMCU Measure distance\" class=\"wp-image-104594\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Thonny IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Installing and getting started with Thonny IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py<\/a><\/li><\/ul><\/li><li>uPyCraft IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with uPyCraft IDE<\/a><\/li><li>Install uPyCraft IDE (<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-windows-pc-instructions\/\">Windows<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-mac-os-x-instructions\/\">Mac OS X<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-linux-ubuntu-instructions\/\">Linux<\/a>)<\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li><\/ul><\/li><\/ul>\n\n\n\n<p>Or, if you&#8217;re familiar with VS Code, you may want to use the PyMakr extension:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-esp32-esp8266-vs-code-pymakr\/\">MicroPython: Program ESP32\/ESP8266 using VS Code and Pymakr<\/a><\/li><\/ul>\n\n\n\n<p class=\"rntbox rntclblue\">Learn more about MicroPython:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with ESP32 and ESP8266 eBook<\/a>.<\/p>\n\n\n\n<p>You might also like reading other HC-SR04 Ultrasonic guides:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-hc-sr04-ultrasonic-arduino\/\"><span style=\"font-size: inherit; background-color: initial;\">ESP32 NodeMCU with HC-SR04 Ultrasonic Sensor with Arduino IDE<\/span><\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-hc-sr04-ultrasonic-arduino\/\">ESP8266 NodeMCU with HC-SR04 Ultrasonic Sensor with Arduino IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/complete-guide-for-ultrasonic-sensor-hc-sr04\/\">Complete Guide for Ultrasonic Sensor HC-SR04 with Arduino<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">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\n<div class=\"wp-block-image\"><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\n<p>The next picture shows the other side of the sensor.<\/p>\n\n\n\n<div class=\"wp-block-image\"><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\n<h2 class=\"wp-block-heading\">Where to Buy HC-SR04 Ultrasonic Sensor?<\/h2>\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\"><li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">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\">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\"><li>The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).<\/li><li>The sound travels through the air. If it finds an object, it bounces back to the module.<\/li><li>The ultrasound receiver (echo pin) receives the reflected sound (echo).<\/li><\/ol>\n\n\n\n<div class=\"wp-block-image\"><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\n<p>Taking into account the sound&#8217;s velocity in the air and the travel time (time passed 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\"><li>speed of sound in the air at 20\u00baC (68\u00baF) = <strong>343m\/s<\/strong><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\n\n\n\n<div class=\"wp-block-image\"><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\/2021\/06\/ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-Demonstration.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 NodeMCU Board HC-SR04 Ultrasonic Sensor Module Arduino Demonstration\" class=\"wp-image-104463\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-Demonstration.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-Demonstration.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\n<p>To complete this tutorial you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\">ESP32<\/a>&nbsp;or&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\">ESP8266<\/a>&nbsp;(read&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/esp32-vs-esp8266\/\" target=\"_blank\">ESP32 vs ESP8266<\/a>)<\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\">Jumper wires<\/a><\/li><\/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 &#8211; ESP32 with HC-SR04 Ultrasonic Sensor<\/h2>\n\n\n\n<p>Wire the HC-SR04 ultrasonic sensor to the ESP32 as shown in the following schematic diagram. We&#8217;re connecting the Trig pin to <span class=\"rnthl rntcgreen\">GPIO 5<\/span> and the Echo pin to <span class=\"rnthl rntclgray\">GPIO 18<\/span>, but you can use any other suitable pins. Go to the next section if you&#8217;re using an ESP8266 board.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"846\" height=\"688\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?resize=846%2C688&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Wiring Ultrasonic Sensor Diagram\" class=\"wp-image-104536\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?w=846&amp;quality=100&amp;strip=all&amp;ssl=1 846w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?resize=300%2C244&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?resize=768%2C625&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 846px) 100vw, 846px\" \/><\/figure><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Ultrasonic Sensor<\/strong><\/td><td><strong>ESP32<\/strong><\/td><\/tr><tr><td>VCC<\/td><td><span class=\"rnthl rntcred\">VIN<\/span><\/td><\/tr><tr><td>Trig<\/td><td><span class=\"rnthl rntcgreen\">GPIO 5<\/span><\/td><\/tr><tr><td>Echo<\/td><td><span class=\"rnthl rntclgray\">GPIO 18<\/span><\/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\/esp32-pinout-reference-gpios\/\">ESP32 Pinout Reference Guide<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"esp32-hcsr04-wiring\">Schematic &#8211; ESP8266 with HC-SR04 Ultrasonic Sensor<\/h2>\n\n\n\n<p>Wire the HC-SR04 ultrasonic sensor to the ESP8266 as shown in the following schematic diagram. We&#8217;re connecting the Trig pin to <span class=\"rnthl rntcgreen\">GPIO 12<\/span> and the Echo pin to <span class=\"rnthl rntclgray\">GPIO 14<\/span>, but you can use any other suitable pins.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"738\" height=\"587\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?resize=738%2C587&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Wiring Ultrasonic Sensor Diagram\" class=\"wp-image-104565\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?w=738&amp;quality=100&amp;strip=all&amp;ssl=1 738w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.png?resize=300%2C239&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 738px) 100vw, 738px\" \/><\/figure><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Ultrasonic Sensor<\/strong><\/td><td><strong>ESP8266<\/strong><\/td><\/tr><tr><td>VCC<\/td><td><span class=\"rnthl rntcred\">VIN<\/span><\/td><\/tr><tr><td>Trig<\/td><td><span class=\"rnthl rntcgreen\">GPIO 12<\/span> (D6)<\/td><\/tr><tr><td>Echo<\/td><td><span class=\"rnthl rntclgray\">GPIO 14<\/span> (D5)<\/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\/esp8266-pinout-reference-gpios\/\">ESP8266 Pinout Reference Guide<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">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 the ESP32\/ESP8266 boards 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 ESP32\/ESP8266 board (save it with the name <em>hcsr04.py<\/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<p>Follow the next set of instructions for the IDE you&#8217;re using:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>A. Upload HC-SR04 library with <strong>uPyCraft IDE<\/strong><\/li><li>B. Upload HC-SR04 library with <strong>Thonny IDE<\/strong><\/li><\/ul>\n\n\n\n<p>Before moving to the next section, make sure you have MicroPython firmware flashed into your ESP32 or ESP8266 boards. You can follow one of the next tutorials:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py on ESP32 and ESP8266<\/a><\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">A. Upload HC-SR04 library with uPyCraft IDE<\/h3>\n\n\n\n<p>This section shows how to upload a library using uPyCraft IDE. If you\u2019re using Thonny IDE, read the next section.<\/p>\n\n\n\n<p>First, make sure you have a connection between the IDE and your board. Go to <strong>Tools <\/strong>&gt; <strong>Serial <\/strong>and select the COM port. Go to <strong>Tools <\/strong>&gt; <strong>Board <\/strong>and select the board. Then, click on the <strong>Connect <\/strong>button.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-connect-disconnect.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"253\" height=\"53\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-connect-disconnect.png?resize=253%2C53&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-75059\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-connect-disconnect.png?w=253&amp;quality=100&amp;strip=all&amp;ssl=1 253w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-connect-disconnect.png?resize=250%2C53&amp;quality=100&amp;strip=all&amp;ssl=1 250w\" sizes=\"(max-width: 253px) 100vw, 253px\" \/><\/a><\/figure><\/div>\n\n\n\n<p> <strong>1.<\/strong>&nbsp;Create a new file by pressing the&nbsp;<strong>New File<\/strong>&nbsp;button (1).<\/p>\n\n\n\n<p><strong>2.<\/strong>&nbsp;Copy the HC-SR04 library code into that 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>3.<\/strong>&nbsp;After copying the code, save the file by pressing the&nbsp;<strong>Save&nbsp;<\/strong>button (2).<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1023\" height=\"662\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/upload-hcsr04-library-micropython-upycraft.png?resize=1023%2C662&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Install HC-SR04 Library MicroPython Upycraft IDE\" class=\"wp-image-104618\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/upload-hcsr04-library-micropython-upycraft.png?w=1023&amp;quality=100&amp;strip=all&amp;ssl=1 1023w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/upload-hcsr04-library-micropython-upycraft.png?resize=300%2C194&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/upload-hcsr04-library-micropython-upycraft.png?resize=768%2C497&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1023px) 100vw, 1023px\" \/><\/figure><\/div>\n\n\n\n<p><strong>4.<\/strong> Call this new file <em>hcsr04.py<\/em> and press <strong>ok<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"402\" height=\"112\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-upycraft-ide.png?resize=402%2C112&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Save HC-SR04 Library Upycraft IDE\" class=\"wp-image-104619\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-upycraft-ide.png?w=402&amp;quality=100&amp;strip=all&amp;ssl=1 402w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-upycraft-ide.png?resize=300%2C84&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 402px) 100vw, 402px\" \/><\/figure><\/div>\n\n\n\n<p>5. Click the <strong>Download and Run<\/strong> (3) button.<\/p>\n\n\n\n<p>After this, the file should be on the device folder with the name hcsr04.py, as highlighted in the following figure.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"938\" height=\"572\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-upycraft-id.png?resize=938%2C572&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-104620\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-upycraft-id.png?w=938&amp;quality=100&amp;strip=all&amp;ssl=1 938w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-upycraft-id.png?resize=300%2C183&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-upycraft-id.png?resize=768%2C468&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 938px) 100vw, 938px\" \/><\/figure><\/div>\n\n\n\n<p>Now, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">B. Upload HC-SR04 library with Thonny IDE<\/h3>\n\n\n\n<p>If you\u2019re using Thonny IDE, follow the next steps:<\/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\n<div class=\"wp-block-image\"><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\n<p><strong>3.<\/strong>&nbsp;Select save to \u201c<strong>MicroPython device<\/strong>\u201c:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"220\" height=\"202\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/Thonny-IDE-ESP32-ESP8266-MicroPython-Save-file-library-to-device-select.png?resize=220%2C202&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE ESP32 ESP8266 MicroPython Save file library to device select\" class=\"wp-image-99605\"\/><\/figure><\/div>\n\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\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"553\" height=\"409\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-thonny-ide.png?resize=553%2C409&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR04 library new MicroPython file Thonny IDE\" class=\"wp-image-104621\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-thonny-ide.png?w=553&amp;quality=100&amp;strip=all&amp;ssl=1 553w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/save-hcsr04-library-thonny-ide.png?resize=300%2C222&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 553px) 100vw, 553px\" \/><\/figure><\/div>\n\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 MicroPython device. Your file should be listed there:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"552\" height=\"273\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-thonny-ide.png?resize=552%2C273&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"HC-SR04 library MicroPython file created Thonny IDE\" class=\"wp-image-104623\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-thonny-ide.png?w=552&amp;quality=100&amp;strip=all&amp;ssl=1 552w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/hc-sr04-library-successfully-installed-thonny-ide.png?resize=300%2C148&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 552px) 100vw, 552px\" \/><\/figure><\/div>\n\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\">Code &#8211; HC-SR04 Ultrasonic Sensor<\/h2>\n\n\n\n<p>After uploading the library to the ESP32 or ESP8266, copy the following code to the <em>main.py<\/em> or <em>boot.py<\/em> file. It simply prints the distance to the closest object every second (example adapted from the <a href=\"https:\/\/github.com\/rsc1975\/micropython-hcsr04\">library page<\/a>).<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-hc-sr04-ultrasonic-esp32-esp8266\/\r\nfrom hcsr04 import HCSR04\r\nfrom time import sleep\r\n\r\n# ESP32\r\nsensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)\r\n\r\n# ESP8266\r\n#sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)\r\n\r\nwhile True:\r\n    distance = sensor.distance_cm()\r\n    print('Distance:', distance, 'cm')\r\n    sleep(1)\r\n<\/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\/main_basic.py\" 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=5, echo_pin=18, echo_timeout_us=10000)<\/code><\/pre>\n\n\n\n<p>If you&#8217;re using the ESP8266, comment the previous line and uncomment the following to use different pins:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)<\/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<\/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>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 = 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:', distance, 'cm')<\/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<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. The distance to the closest object should be printed on the shell.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"787\" height=\"373\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-ESP8266-HC-SR04-Demonstration-MicroPython-Thonny-IDE.png?resize=787%2C373&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 ESP8266 with HC-SR04 MicroPython Demonstration\" class=\"wp-image-104625\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-ESP8266-HC-SR04-Demonstration-MicroPython-Thonny-IDE.png?w=787&amp;quality=100&amp;strip=all&amp;ssl=1 787w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-ESP8266-HC-SR04-Demonstration-MicroPython-Thonny-IDE.png?resize=300%2C142&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-ESP8266-HC-SR04-Demonstration-MicroPython-Thonny-IDE.png?resize=768%2C364&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 787px) 100vw, 787px\" \/><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">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\n<div class=\"wp-block-image\"><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\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Parts.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython ESP32 ESP8266 NodeMCU Board HC-SR04 Ultrasonic Sensor Module Arduino OLED Demonstration\" class=\"wp-image-104630\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Parts.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Parts.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\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\n\n\n\n<p>Here&#8217;s a list with the parts required to complete this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\" id=\"block-20d88f2a-6847-4e0b-a050-3bc5f026cbe4\"><li><a href=\"https:\/\/makeradvisor.com\/tools\/ultrasonic-sensor-hc-sr04\/\" target=\"_blank\" rel=\"noreferrer noopener\">HC-SR04 Ultrasonic Sensor<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\">ESP32<\/a>&nbsp;or&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\">ESP8266<\/a>&nbsp;(read&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/esp32-vs-esp8266\/\" target=\"_blank\">ESP32 vs ESP8266<\/a>)<\/li><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><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\">Jumper wires<\/a><\/li><\/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. Follow the schematic diagram for the board you&#8217;re using.<\/p>\n\n\n\n<p><strong>ESP32<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?resize=750%2C1035&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 with HC-SR04 and OLED Display Wiring Diagram\" class=\"wp-image-104557\" width=\"750\" height=\"1035\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?resize=217%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 217w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?resize=742%2C1024&amp;quality=100&amp;strip=all&amp;ssl=1 742w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p><strong>ESP8266<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"1008\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-NodeMCU-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?resize=750%2C1008&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 NodeMCU with HC-SR04 and OLED Display Wiring Diagram\" class=\"wp-image-104568\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-NodeMCU-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP8266-NodeMCU-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.png?resize=223%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 223w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\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\"><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><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 to the display.<\/li><li><strong><em>main.py<\/em><\/strong>: this is the main script to get the distance and display it on the OLED display.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">ssd1306.py<\/h3>\n\n\n\n<p>Create a new file called <em>ss1306.py<\/em> and copy the following code. Then, upload it to your board.<\/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.<\/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 <em>main.py<\/em> file is where we&#8217;ll get the distance and display it on the OLED display.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-hc-sr04-ultrasonic-esp32-esp8266\/\r\nfrom machine import Pin, I2C\r\nimport ssd1306\r\nfrom hcsr04 import HCSR04\r\nfrom time import sleep\r\n\r\n# ESP32 Pin assignment \r\ni2c = I2C(scl=Pin(22), sda=Pin(21))\r\nsensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)\r\n\r\n# ESP8266 Pin assignment\r\n#i2c = I2C(scl=Pin(5), sda=Pin(4))\r\n#sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)\r\n\r\noled_width = 128\r\noled_height = 64\r\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)\r\n\r\nwhile True:\r\n  oled.fill(0)\r\n  #oled.show()\r\n  distance = sensor.distance_mm()\r\n  print('Distance:', distance, 'mm')\r\n  oled.text(&quot;Distance (mm)&quot;, 0, 15)\r\n  oled.text(str(distance), 0, 35)\r\n  oled.show()\r\n  sleep(1)<\/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\/main_oled.py\" 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 ESP32 and ESP8266 boards using MicroPython, refer to the next tutorials:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-oled-display-esp32-esp8266\/\">MicroPython: OLED Display with ESP32 and ESP8266<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-ssd1306-oled-scroll-shapes-esp32-esp8266\/\">MicroPython: SSD1306 OLED Display Scroll Functions and Draw Shapes (ESP32\/ESP8266)<\/a><\/li><\/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=12, echo_pin=14, 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>On the <span class=\"rnthl rntliteral\">while<\/span> loop is where we&#8217;ll get the distance and display it on the OLED. <\/p>\n\n\n\n<p>First, 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>Get the distance in mm and save it in the <span class=\"rnthl rntliteral\">distance<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>distance = sensor.distance_mm()<\/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>Display the distance on the display. Notice that you need to convert the distance to a string using the <span class=\"rnthl rntliteral\">str()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>oled.text(\"Distance (mm)\", 0, 15)\noled.text(str(distance), 0, 35)<\/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-c\"><code>sleep(1)<\/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 ESP32 or ESP8266 board in the following order:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><em>ssd1306.py<\/em><\/li><li><em>hcsr04.py<\/em><\/li><li><em>main.py<\/em><\/li><\/ol>\n\n\n\n<p>If you don&#8217;t know how to upload code, you can read our getting started guides with uPyCraft IDE, Thonny IDE or VS Code + PyMakr:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Getting Started with Thonny MicroPython (Python) IDE for ESP32 and ESP8266<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with MicroPython on ESP32 and ESP8266 (uPyCraft IDE)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-esp32-esp8266-vs-code-pymakr\/\">MicroPython: Program ESP32\/ESP8266 using VS Code and Pymakr<\/a><\/li><\/ul>\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\n<div class=\"wp-block-image\"><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\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Demonstration.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython ESP32 ESP8266 NodeMCU Board HC-SR04 Ultrasonic Sensor Module Arduino OLED Parts Required\" class=\"wp-image-104631\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Demonstration.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-ESP32-ESP8266-NodeMCU-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Demonstration.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\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 with MicroPython with other popular sensors that you may like:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-bme680-esp32-esp8266\/\">MicroPython: <strong>BME680<\/strong> with ESP32 and ESP8266 (Temperature, Humidity, Pressure, Gas)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-ds18b20-esp32-esp8266\/\">MicroPython: <strong>DS18B20 <\/strong>Temperature Sensor with ESP32 and ESP8266<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-bme280-esp32-esp8266\/\">MicroPython: <strong>BME280 <\/strong>with ESP32 and ESP8266 (Pressure, Temperature, Humidity)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\">MicroPython: ESP32\/ESP8266 with <strong>DHT11\/DHT22<\/strong> Temperature and Humidity Sensor<\/a><\/li><\/ul>\n\n\n\n<p>You can check all our <a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32-esp8266-micropython\/\">MicroPython projects here<\/a>. <\/p>\n\n\n\n<p>If you want to learn more about programming the ESP32 and ESP8266 boards with MicroPython, get access to our eBook:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\"><strong>MicroPython Programming with ESP32 and ESP8266<\/strong><\/a><strong>. <\/strong><\/p>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you&#8217;ll learn how to use the HC-SR04 Ultrasonic Sensor with the ESP32 and ESP8266 to get the distance to an object using MicroPython firmware. This tutorial covers &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"MicroPython: HC-SR04 Ultrasonic Sensor with ESP32 and ESP8266 (Measure distance)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/micropython-hc-sr04-ultrasonic-esp32-esp8266\/#more-104589\" aria-label=\"Read more about MicroPython: HC-SR04 Ultrasonic Sensor with ESP32 and ESP8266 (Measure distance)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":104594,"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":[310,309,264],"tags":[],"class_list":["post-104589","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-micropython","category-0-esp32-micropython","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/MicroPython-HC-SR04-Ultrasonic-Sensor-ESP32-ESP8266-Measure-distance.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/104589","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=104589"}],"version-history":[{"count":17,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/104589\/revisions"}],"predecessor-version":[{"id":106409,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/104589\/revisions\/106409"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/104594"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=104589"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=104589"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=104589"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}