Distance Measurement With ESP32: HC-SR04 Ultrasonic Sensor Guide

by AKP in Circuits > Arduino

181 Views, 1 Favorites, 0 Comments

Distance Measurement With ESP32: HC-SR04 Ultrasonic Sensor Guide

esp32-hc-sr04-ultrasonic-arduino.jpg

This tutorial illustrates how to use the HC-SR04 Ultrasonic Sensor with the ESP32 board using the Arduino core. The sensor employs sonar technology to determine the distance to an object. We will walk you through the steps of connecting the sensor to the ESP32 and provide several example sketches for measuring the distance to an object with the HC-SR04.

HC-SR04 Ultrasonic Sensor Overview

HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Front.jpg
HC-SR04-Ultrasonic-Sensor-Module-Distance-Measurement-Component-Part-Back.jpg

The HC-SR04 ultrasonic sensor utilizes sonar for distance measurement to an object. It can measure distances ranging from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), making it suitable for various hobbyist projects. Additionally, this module includes ultrasonic transmitter and receiver modules.

The image below illustrates the HC-SR04 ultrasonic sensor.

The subsequent image reveals the reverse side of the sensor.

How Does the HC-SR04 Ultrasonic Sensor Operate?

how-ultrasonic-sensor-works-01.jpg

The ultrasonic sensor employs sonar technology to determine the distance to an object. Here’s a breakdown of its functioning:

  1. The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
  2. The emitted sound travels through the air, and if it encounters an object, it reflects back to the module.
  3. The ultrasound receiver (echo pin) picks up the reflected sound (echo).

By considering the speed of sound in the air and the time it takes for the signal to travel (elapsed time since transmission and reception), we can calculate the distance to an object. The formula for this calculation is as follows:

distance to an object = ((speed of sound in the air)*time)/2
  • speed of sound in the air at 20ºC (68ºF) = 343m/s

Schematic – ESP32 With HC-SR04 Ultrasonic Sensor

ESP32-Ultrasonic-Sensor-Wiring-Fritzing-Diagram.jpg

Wire the HC-SR04 ultrasonic sensor to the ESP32 as shown in the following schematic diagram. We’re connecting the Trig pin to GPIO 5 and the Echo pin to GPIO 18, but you can use any other suitable pins.

Code – Getting Distance to an Object Using the HC-SR04 Ultrasonic Sensor and ESP32

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.

/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-hc-sr04-ultrasonic-arduino/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/

const int trigPin = 5;
const int echoPin = 18;

//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701

long duration;
float distanceCm;
float distanceInch;

void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;

// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;

// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);

delay(1000);
}

Upload the code to your board and it will work straight away. Continue reading if you want to learn how the code works or skip to the demonstration section.

ESP32 With HC-SR04 and OLED Display

ESP32-Board-HC-SR04-Ultrasonic-Sensor-Module-Arduino-OLED-Parts.jpg
ESP32-Ultrasonic-Sensor-I2C-OLED-Display-Wiring-Diagram.jpg

In this section, we provide a straightforward example featuring the ESP32, demonstrating the presentation of distance on an I2C OLED display.

For a more comprehensive understanding of how the project functions, we recommend referring to our ESP32 tutorial involving the I2C OLED display.

Schematic Diagram – ESP32 with HC-SR04 and OLED Display

Connect all the components according to the schematic diagram given below.

Code – ESP32 Display Distance (HC-SR04) on OLED Display

/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-hc-sr04-ultrasonic-arduino/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

const int trigPin = 5;
const int echoPin = 18;

//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701

long duration;
int distanceCm;
int distanceInch;

void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input

if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
delay(500);
display.clearDisplay();

display.setTextSize(2);
display.setTextColor(WHITE);
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;

// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;

// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);

display.clearDisplay();
display.setCursor(0, 25);
//Display distance in cm
display.print(distanceCm);
display.print(" cm");

// Display distance in inches
/* display.print(distanceInch);
display.print(" in");*/
display.display();

delay(500);
}


See Full Article Here