{"id":104435,"date":"2021-07-20T18:03:33","date_gmt":"2021-07-20T18:03:33","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=104435"},"modified":"2021-07-27T08:55:17","modified_gmt":"2021-07-27T08:55:17","slug":"esp32-hc-sr04-ultrasonic-arduino","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp32-hc-sr04-ultrasonic-arduino\/","title":{"rendered":"ESP32 with HC-SR04 Ultrasonic Sensor with Arduino IDE"},"content":{"rendered":"\n<p>This guide shows how to use the HC-SR04 Ultrasonic Sensor with the ESP32 board using the Arduino core. The ultrasonic sensor uses sonar to determine the distance to an object. We&#8217;ll show you how to wire the sensor to the ESP32 and provide several example sketches to determine the distance to an object using the HC-SR04.<\/p>\n\n\n\n<div class=\"wp-block-image\"><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\/2021\/06\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 with HC-SR04 Ultrasonic Sensor Module with Arduino IDE\" class=\"wp-image-104458\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.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\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.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\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<p>This tutorial covers the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"#ultrasonic-sensor-pinout\">Ultrasonic Sensor HC-SR04 Pinout<\/a><\/li><li><a href=\"#esp32-hcsr04-wiring\">Wiring the Ultrasonic Sensor HC-SR04 to the ESP32<\/a><\/li><li><a href=\"#ESP32-get-distance-HCSR04\">Getting Distance to an Object Using the Ultrasonic Sensor HC-SR04 with the ESP32<\/a><\/li><li><a href=\"#esp32-HC-SR04-OLED-Display\">Displaying the Distance to an Object on a Display Using the ESP32 and HC-SR04<\/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<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 sensor&nbsp;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 the  HC-SR04 Ultrasonic Sensor Module 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\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Board HC-SR04 Ultrasonic Sensor Module Arduino Parts required\" class=\"wp-image-104460\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino.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 href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP32&nbsp;<\/a>(read&nbsp;<a href=\"https:\/\/makeradvisor.com\/esp32-development-boards-review-comparison\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best ESP32 development boards<\/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\" id=\"esp32-hcsr04-wiring\">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.<\/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 Circuit 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<h2 class=\"wp-block-heading\">Preparing Arduino IDE<\/h2>\n\n\n\n<p>We&#8217;ll program the ESP32 board using Arduino IDE. So, make sure you have the ESP32 add-on installed. Follow the next tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-windows-instructions\/\">Install the ESP32 Board in Arduino IDE<\/a><\/li><\/ul>\n\n\n\n<p>If you want to use VS Code with the PlatformIO extension, follow the next tutorial instead to learn how to program the ESP32:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/vs-code-platformio-ide-esp32-esp8266-arduino\/\">Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266 (Windows, Mac OS X, Linux Ubuntu)<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ESP32-get-distance-HCSR04\">Code &#8211; Getting Distance to an Object using the HC-SR04 Ultrasonic Sensor and ESP32<\/h2>\n\n\n\n<p>The following sketch is a simple example of how you can get the distance between the sensor and an object using the ESP32 board with the Arduino core.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-hc-sr04-ultrasonic-arduino\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*********\/\n\nconst int trigPin = 5;\nconst int echoPin = 18;\n\n\/\/define sound speed in cm\/uS\n#define SOUND_SPEED 0.034\n#define CM_TO_INCH 0.393701\n\nlong duration;\nfloat distanceCm;\nfloat distanceInch;\n\nvoid setup() {\n  Serial.begin(115200); \/\/ Starts the serial communication\n  pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\n  pinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input\n}\n\nvoid loop() {\n  \/\/ Clears the trigPin\n  digitalWrite(trigPin, LOW);\n  delayMicroseconds(2);\n  \/\/ Sets the trigPin on HIGH state for 10 micro seconds\n  digitalWrite(trigPin, HIGH);\n  delayMicroseconds(10);\n  digitalWrite(trigPin, LOW);\n  \n  \/\/ Reads the echoPin, returns the sound wave travel time in microseconds\n  duration = pulseIn(echoPin, HIGH);\n  \n  \/\/ Calculate the distance\n  distanceCm = duration * SOUND_SPEED\/2;\n  \n  \/\/ Convert to inches\n  distanceInch = distanceCm * CM_TO_INCH;\n  \n  \/\/ Prints the distance in the Serial Monitor\n  Serial.print(&quot;Distance (cm): &quot;);\n  Serial.println(distanceCm);\n  Serial.print(&quot;Distance (inch): &quot;);\n  Serial.println(distanceInch);\n  \n  delay(1000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_HC_SR04.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Upload the code to your board and it will work straight away. Continue reading if you want to learn how the code works or skip to the <a href=\"#basic-demonstration\">demonstration section<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>First, define the trigger and the echo pins. <\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const int trigPin = 5;\nconst int echoPin = 18;<\/code><\/pre>\n\n\n\n<p>In this example, we&#8217;re using <span class=\"rnthl rntcgreen\">GPIO 5<\/span> and <span class=\"rnthl rntclgray\">GPIO 18<\/span>. But you can use any other suitable GPIOs\u2014read <a href=\"https:\/\/randomnerdtutorials.com\/esp32-pinout-reference-gpios\/\">ESP32 Pinout Reference: Which GPIO pins should you use?<\/a><\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">SOUND_SPEED<\/span> variable saves the velocity of sound in the air at 20\u00baC. We&#8217;re using the value in cm\/uS.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define SOUND_SPEED 0.034<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">CM_TO_INCH<\/span> variable allows us to convert distance in centimeters to inches.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define CM_TO_INCH 0.393701<\/code><\/pre>\n\n\n\n<p>Then, initialize the following variables.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>long duration;\nfloat distanceCm;\nfloat distanceInch;<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">duration<\/span> variable saves the travel time of the ultrasonic waves (time elapsed since transmission and reception of the pulse wave). The <span class=\"rnthl rntliteral\">distanceCm<\/span> and <span class=\"rnthl rntliteral\">distanceInch<\/span>, as the names suggest, save the distance to an object in centimeters and inches.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">setup()<\/h3>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, initialize a serial communication at a baud rate of 115200 so that we can print the measurements on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200); \/\/ Starts the serial communication<\/code><\/pre>\n\n\n\n<p>Define the trigger pin as an <span class=\"rnthl rntliteral\">OUTPUT<\/span>\u2014the trigger pin emits the ultrasound. And define the echo pin as an <span class=\"rnthl rntliteral\"> INPUT<\/span>\u2014the echo pin receives the reflected wave and sends a signal to the ESP32 that is proportional to the travel time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\npinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">loop()<\/h3>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span>, the following lines produce a 10uS <span class=\"rnthl rntliteral\">HIGH<\/span> pulse on the trigger pin\u2014this means the pin will emit an ultrasound. Note that before sending the pulse, we give a short <span class=\"rnthl rntliteral\">LOW<\/span> pulse to ensure you&#8217;ll get a clean <span class=\"rnthl rntliteral\">HIGH<\/span> pulse.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Clears the trigPin\ndigitalWrite(trigPin, LOW);\ndelayMicroseconds(2);\n\/\/ Sets the trigPin on HIGH state for 10 micro seconds\ndigitalWrite(trigPin, HIGH);\ndelayMicroseconds(10);\ndigitalWrite(trigPin, LOW);<\/code><\/pre>\n\n\n\n<p>We use the <span class=\"rnthl rntliteral\">pulseIn()<\/span> function to get the sound wave travel time:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>duration = pulseIn(echoPin, HIGH);<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclgreen\">The <span class=\"rnthl rntliteral\">pulseIn()<\/span> function reads a HIGH or a LOW pulse on a pin. It accepts as arguments the pin and the state of the pulse (either HIGH or LOW). It returns the length of the pulse in microseconds. The pulse length corresponds to the time it took to travel to the object plus the time traveled on the way back.<\/p>\n\n\n\n<p>Then, we simply calculate the distance to an object taking into account the sound speed.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>distanceCm = duration * SOUND_SPEED\/2;<\/code><\/pre>\n\n\n\n<p>Convert the distance to inches:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>distanceInch = distanceCm * CM_TO_INCH;<\/code><\/pre>\n\n\n\n<p>And finally, print the results on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.print(\"Distance (cm): \");\nSerial.println(distanceCm);\nSerial.print(\"Distance (inch): \");\nSerial.println(distanceInch);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"basic-demonstration\">Demonstration<\/h2>\n\n\n\n<p>Upload the code to your board. Don&#8217;t forget to select the board you&#8217;re using in <strong>Tools <\/strong>&gt; <strong>Boards<\/strong>. Also, don&#8217;t forget to select the right COM port in <strong>Tools <\/strong>&gt; <strong>Port<\/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=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-Demonstration.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Board HC-SR04 Ultrasonic Sensor Module Arduino Demonstration\" class=\"wp-image-104461\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-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\/ESP32-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>After uploading, open the Serial Monitor at a baud rate of 115200. Press the on-board RST button to restart the board and it will start printing the distance to the closest object on the Serial Monitor. Something as shown in the picture below.<\/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=\"601\" height=\"525\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Ultrasonic-Sensor-ESP32-ESP8266-Get-Distance-To-An-Object-Arduino.png?resize=601%2C525&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Ultrasonic Sensor ESP32 ESP8266 Get Distance to an Object Arduino\" class=\"wp-image-104538\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Ultrasonic-Sensor-ESP32-ESP8266-Get-Distance-To-An-Object-Arduino.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/Ultrasonic-Sensor-ESP32-ESP8266-Get-Distance-To-An-Object-Arduino.png?resize=300%2C262&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"esp32-HC-SR04-OLED-Display\">ESP32 with HC-SR04 and OLED Display<\/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\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Parts.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Board HC-SR04 Ultrasonic Sensor Module Arduino OLED Parts Required\" class=\"wp-image-104578\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-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\/ESP32-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<p>In this section, we&#8217;ll show you a simple example with the ESP32 that displays the distance on an I2C OLED display.<\/p>\n\n\n\n<p>To better understand how the project works, we recommend taking a look at our <a href=\"https:\/\/randomnerdtutorials.com\/esp32-ssd1306-oled-display-arduino-ide\/\">ESP32 tutorial with the I2C OLED display<\/a>.<\/p>\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 style=\"font-size: inherit;\" href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP32&nbsp;<\/a><span style=\"font-size: inherit;\">(read&nbsp;<\/span><a style=\"font-size: inherit;\" href=\"https:\/\/makeradvisor.com\/esp32-development-boards-review-comparison\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best ESP32 development boards<\/a><span style=\"font-size: inherit;\">)<\/span><\/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<h3 class=\"wp-block-heading\">Schematic Diagram &#8211; ESP32 with HC-SR04 and OLED Display<\/h3>\n\n\n\n<p>Wire all the parts as shown in the following schematic diagram.<\/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=\"1035\" 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 Circuit Diagram\" class=\"wp-image-104557\" 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 class=\"rntbox rntclblue\">Learn more about the OLED display with the ESP32: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-ssd1306-oled-display-arduino-ide\/\">ESP32 OLED Display with Arduino IDE<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Code &#8211; ESP32 Display Distance (HC-SR04) on OLED Display<\/h3>\n\n\n\n<p>To use this example, make sure you have the Adafruit SSD1306 and Adafruit GFX libraries installed. You can install these libraries through the Arduino Library Manager.<\/p>\n\n\n\n<p>Go to <strong>Sketch <\/strong>&gt; <strong>Library<\/strong> &gt; <strong>Manage Libraries<\/strong>, search for &#8220;<strong>SSD1306,<\/strong>&#8221; and install the SSD1306 library from Adafruit.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"788\" height=\"443\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-ssd1306-adafruit-library.png?resize=788%2C443&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Install Library I2C OLED Display SSD1306 Arduino IDE\" class=\"wp-image-85156\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-ssd1306-adafruit-library.png?w=788&amp;quality=100&amp;strip=all&amp;ssl=1 788w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-ssd1306-adafruit-library.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-ssd1306-adafruit-library.png?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 788px) 100vw, 788px\" \/><\/figure><\/div>\n\n\n\n<p>After installing the SSD1306 library from Adafruit, type \u201c<strong>GFX<\/strong>\u201d in the search box and install the library.<\/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=\"786\" height=\"443\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-gfx-library-adafruit.png?resize=786%2C443&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Installing GFX Library ESP8266 ESP32 Arduino\" class=\"wp-image-85157\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-gfx-library-adafruit.png?w=786&amp;quality=100&amp;strip=all&amp;ssl=1 786w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-gfx-library-adafruit.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/05\/install-gfx-library-adafruit.png?resize=768%2C433&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 786px) 100vw, 786px\" \/><\/figure><\/div>\n\n\n\n<p>After installing the libraries, restart your Arduino IDE.<\/p>\n\n\n\n<p>Then, simply copy the following code to your Arduino IDE and upload the code to the board.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-hc-sr04-ultrasonic-arduino\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*********\/\n\n#include &lt;Wire.h&gt;\n#include &lt;Adafruit_GFX.h&gt;\n#include &lt;Adafruit_SSD1306.h&gt;\n\n#define SCREEN_WIDTH 128 \/\/ OLED display width, in pixels\n#define SCREEN_HEIGHT 64 \/\/ OLED display height, in pixels\n\n\/\/ Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)\nAdafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, -1);\n\nconst int trigPin = 5;\nconst int echoPin = 18;\n\n\/\/define sound speed in cm\/uS\n#define SOUND_SPEED 0.034\n#define CM_TO_INCH 0.393701\n\nlong duration;\nint distanceCm;\nint distanceInch;\n\nvoid setup() {\n  Serial.begin(115200);\n  pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\n  pinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input\n\n  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {\n    Serial.println(F(&quot;SSD1306 allocation failed&quot;));\n    for(;;);\n  }\n  delay(500);\n  display.clearDisplay();\n\n  display.setTextSize(2);\n  display.setTextColor(WHITE);\n}\n\nvoid loop() {\n  \/\/ Clears the trigPin\n  digitalWrite(trigPin, LOW);\n  delayMicroseconds(2);\n  \/\/ Sets the trigPin on HIGH state for 10 micro seconds\n  digitalWrite(trigPin, HIGH);\n  delayMicroseconds(10);\n  digitalWrite(trigPin, LOW);\n  \n  \/\/ Reads the echoPin, returns the sound wave travel time in microseconds\n  duration = pulseIn(echoPin, HIGH);\n  \n  \/\/ Calculate the distance\n  distanceCm = duration * SOUND_SPEED\/2;\n  \n  \/\/ Convert to inches\n  distanceInch = distanceCm * CM_TO_INCH;\n  \n  \/\/ Prints the distance in the Serial Monitor\n  Serial.print(&quot;Distance (cm): &quot;);\n  Serial.println(distanceCm);\n  Serial.print(&quot;Distance (inch): &quot;);\n  Serial.println(distanceInch);\n\n  display.clearDisplay();\n  display.setCursor(0, 25);\n  \/\/Display distance in cm\n  display.print(distanceCm);\n  display.print(&quot; cm&quot;);\n  \n  \/\/ Display distance in inches\n  \/* display.print(distanceInch);\n  display.print(&quot; in&quot;);*\/\n  display.display(); \n\n  delay(500);  \n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_HC_SR04_OLED.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Start by including the required libraries for the OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;Wire.h&gt;\n#include &lt;Adafruit_GFX.h&gt;\n#include &lt;Adafruit_SSD1306.h&gt;<\/code><\/pre>\n\n\n\n<p>Define the width and height of the OLED display. We&#8217;re using a 128&#215;64 OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define SCREEN_WIDTH 128 \/\/ OLED display width, in pixels\n#define SCREEN_HEIGHT 64 \/\/ OLED display height, in pixels<\/code><\/pre>\n\n\n\n<p>Create an <span class=\"rnthl rntliteral\">Adafruit_SSD1306<\/span> object called <span class=\"rnthl rntliteral\">display<\/span> to handle the OLED display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &amp;Wire);<\/code><\/pre>\n\n\n\n<p>Define the pins that the HC-SR04 sensor is connected to.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>const int trigPin = 5;\nconst int echoPin = 18;<\/code><\/pre>\n\n\n\n<p>Create variables to save the distance and the duration between the transmission and reception of the sound waves.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>long duration;\nint distanceCm;\nint distanceInch;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">setup()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, initialize a serial communication at a baud rate of 115200 so that we can print the results on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>Define the trigger pin as an <span class=\"rnthl rntliteral\">OUTPUT<\/span> and the echo pin as an <span class=\"rnthl rntliteral\">INPUT<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>pinMode(trigPin, OUTPUT); \/\/ Sets the trigPin as an Output\npinMode(echoPin, INPUT); \/\/ Sets the echoPin as an Input<\/code><\/pre>\n\n\n\n<p>Initialize the OLED display:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {\n  Serial.println(F(\"SSD1306 allocation failed\"));\n  for(;;);\n}<\/code><\/pre>\n\n\n\n<p>Set the font size and color for the display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.setTextSize(2);\ndisplay.setTextColor(WHITE);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">loop()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span> is where we&#8217;ll get the distance and display it on the OLED.<\/p>\n\n\n\n<p>Get the distance (we&#8217;ve already explained in the previous section how to calculate the distance).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Clears the trigPin\ndigitalWrite(trigPin, LOW);\ndelayMicroseconds(2);\n\/\/ Sets the trigPin on HIGH state for 10 micro seconds\ndigitalWrite(trigPin, HIGH);\ndelayMicroseconds(10);\ndigitalWrite(trigPin, LOW);\n  \n\/\/ Reads the echoPin, returns the sound wave travel time in microseconds\nduration = pulseIn(echoPin, HIGH);\n  \n\/\/ Calculate the distance\ndistanceCm = duration * SOUND_SPEED\/2;\n  \n\/\/ Convert to inches\ndistanceInch = distanceCm * CM_TO_INCH;<\/code><\/pre>\n\n\n\n<p>Print the distance on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Prints the distance on the Serial Monitor\nSerial.print(\"Distance (cm): \");\nSerial.println(distanceCm);\nSerial.print(\"Distance (inch): \");\nSerial.println(distanceInch);<\/code><\/pre>\n\n\n\n<p>Clear the display in each <span class=\"rnthl rntliteral\">loop()<\/span> to write new readings.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.clearDisplay();<\/code><\/pre>\n\n\n\n<p>Set the display cursor to (0, 25).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.setCursor(0, 25);<\/code><\/pre>\n\n\n\n<p>The following lines print the distance in centimeters in the OLED display.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Display static text\ndisplay.print(distanceCm);\ndisplay.print(\" cm\");<\/code><\/pre>\n\n\n\n<p>Comment the previous lines and uncomment the following lines if you want to display the readings in inches.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/* Display distance in inches\ndisplay.print(distanceInch);\ndisplay.print(\" in\");*\/<\/code><\/pre>\n\n\n\n<p>Lastly, call <span class=\"rnthl rntliteral\">display.display()<\/span> to actually show the readings on the OLED.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>display.display();<\/code><\/pre>\n\n\n\n<p>The distance is updated every 500 milliseconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>delay(500);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Demonstration<\/h3>\n\n\n\n<p>Upload the code to your ESP32 board. Go to <strong>Tools <\/strong>&gt; <strong>Board <\/strong>and select the ESP32 board you\u2019re using. Go to <strong>Tools <\/strong>&gt; <strong>Port <\/strong>and select the port your board is connected to. Then, click the upload button.<\/p>\n\n\n\n<p>Open the Serial Monitor at a baud rate of 115200, press the on-board RST button. The sensor measurements will be displayed both on the Serial Monitor and the OLED display.<\/p>\n\n\n\n<p>Approximate an object to the sensor and see the values changing.<\/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\/ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Demonstration.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Board HC-SR04 Ultrasonic Sensor Module Arduino OLED Demonstration\" class=\"wp-image-104579\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-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\/ESP32-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<p>You can watch a quick video demonstration:<\/p>\n\n\n<div style=\"text-align:center\"><iframe src=\"https:\/\/player.vimeo.com\/video\/577280654?color=ff9933&title=1&byline=0&portrait=0\" width=\"720\" height=\"405\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen><\/iframe><\/div><\/br>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>The HC-SR04 Ultrasonic Sensor allows us to determine the distance to an object. In this tutorial you&#8217;ve learned how to use the HC-SR04 with the ESP32. We have tutorials for other popular sensors that you may like:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide\/\">ESP32 with&nbsp;<strong>DHT11\/DHT22 Temperature and Humidity Sensor<\/strong>&nbsp;using Arduino IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-bme280-arduino-ide-pressure-temperature-humidity\/\">ESP32 with&nbsp;<strong>BME280<\/strong>&nbsp;using Arduino IDE (<strong>Pressure, Temperature, Humidity<\/strong>)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-bme680-sensor-arduino\/\">ESP32 with <strong>BME680 Environmental Sensor<\/strong> using Arduino IDE (Gas, Pressure, Humidity, Temperature)<\/a><\/li><li><a style=\"font-size: inherit;\" href=\"https:\/\/randomnerdtutorials.com\/esp32-ds18b20-temperature-arduino-ide\/\">ESP32<strong>&nbsp;DS18B20 Temperature Sensor<\/strong>&nbsp;with Arduino IDE (Single, Multiple, Web Server)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-with-bmp180-barometric-sensor\/\">ESP32 with&nbsp;<strong>BMP180 Barometric Sensor<\/strong>&nbsp;(Temperature and Pressure)<\/a><\/li><\/ul>\n\n\n\n<p>Learn more about the ESP32 with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE (eBook + video course)<\/a><\/strong><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with ESP32 and ESP8266 eBook (2nd Edition)<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32\/\">More ESP32 Projects and Tutorials\u2026<\/a><\/li><\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This guide shows how to use the HC-SR04 Ultrasonic Sensor with the ESP32 board using the Arduino core. The ultrasonic sensor uses sonar to determine the distance to an object. &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP32 with HC-SR04 Ultrasonic Sensor with Arduino IDE\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp32-hc-sr04-ultrasonic-arduino\/#more-104435\" aria-label=\"Read more about ESP32 with HC-SR04 Ultrasonic Sensor with Arduino IDE\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":104458,"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":[281,276,277,299,264],"tags":[],"class_list":["post-104435","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32-project","category-esp32","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/06\/ESP32-HC-SR04-Ultrasonic-Sensor-with-Arduino-IDE-Tutorial.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\/104435","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=104435"}],"version-history":[{"count":28,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/104435\/revisions"}],"predecessor-version":[{"id":105389,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/104435\/revisions\/105389"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/104458"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=104435"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=104435"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=104435"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}