How HC-SR04 Ultrasonic Sensor Works & Interface It With Arduino

The HC-SR04 Ultrasonic Distance Sensor, which can report the range of objects up to 13 feet away, can give your next Arduino project bat-powers. When attempting to prevent your robot from colliding with a wall, this is important information to have. They are inexpensive, simple to the interface, low power (ideal for battery-operated devices), and very well-liked by enthusiasts.

 

What is Ultrasound?

A high-pitched sound wave with a frequency outside the range of human hearing.

Sound waves vibrating between 20 times per second (a deep rumbling noise) and 20,000 times per second can be heard by humans (a high-pitched whistle). However, ultrasound is inaudible to humans since it has a frequency of more than 20,000 Hz.

HC-SR04 Hardware Overview

Two ultrasonic transducers make up an HC-SR04 ultrasonic distance sensor.

One functions as a transmitter, converting the electrical signal into pulses of ultrasonic sound at a frequency of 40 KHz. One operates as a receiver and searches for the pulses being transmitted.

These pulses are received by the receiver, which then generates an output pulse whose width is related to the proximity of the object in front.

With an accuracy of 3 mm, this sensor offers excellent non-contact range detection from 2 cm to 400 cm (about 13 feet).

It may be immediately linked to an Arduino or any other 5V logic microcontroller because it runs on 5 volts.

Technical Specifications

Operating Voltage DC 5V
Operating Current 15mA
Operating Frequency 40KHz
Max Range 4m
Min Range 2cm
Ranging Accuracy 3mm
Measuring Angle 15 degree
Trigger Input Signal 10µS TTL pulse
Dimension 45 x 20 x 15mm

HC-SR04 Ultrasonic Sensor Pinout

  VCC gives the HC-SR04 ultrasonic sensor power. It can be connected to your Arduino’s 5V output.
  Trig (Trigger) To start ultrasonic sound pulses, this pin is used. The sensor starts an ultrasonic burst by setting this pin HIGH for 10 s.
  Echo When an ultrasonic burst is broadcast, the pin goes high. It stays high until the sensor gets an echo, at which point it becomes low. The distance can be determined by counting the number of seconds the Echo pin remains up.
  GND The ground pin is to Attach to the Arduino’s ground.

How Does HC-SR04 Ultrasonic Distance Sensor Work?

The trigger pin must be HIGH for 10 seconds to begin. The sensor responds by sending an eight-pulse burst of ultrasonic data at a frequency of 40 kHz. This eight-pulse pattern was specifically created to allow the receiver to differentiate between the transmitted pulses and background ultrasonic noise.

These eight ultrasonic pulses move away from the transmitter via the air. The echo pin goes HIGH in the interim to start the echo-back signal.

After 38 ms, the echo signal times out and becomes low if those pulses are not reflected back (38 milliseconds). Thus, a pulse of 38 ms shows that there is no obstruction within the sensor’s field of view.

As soon as the signal is received, the echo pin goes low if those pulses are reflected back. Depending on how long it takes to receive the signal, this causes a pulse to be generated on the echo pin that ranges in width from 150 s to 25 ms.

Calculating the Distance

The distance from the reflected object is determined using the width of the received pulse. The straightforward distance-speed-time equation we learned in high school can be used to calculate this. The equation can be quickly recalled by arranging the letters into a triangle.

To better explain, let’s use an example. Let’s say we have an unknown-sized object in front of the sensor and we detect a 500-second pulse on the echo pin. Let’s now determine the object’s distance from the sensor. The equation below will be used for this.

Distance = Speed x Time

Here, we know the speed and the value of time, which is 500 seconds. It must be sound speed, of course! There is 340 m/s. We must translate the sound speed into cm/s in order to get the distance. It moves at 0.034 cm/s. Now that we have that knowledge, we can determine the distance!

Distance = 0.034 cm/µs x 500 µs

We’re not done yet, though! Keep in mind that the echo pulse represents the duration of the signal’s transmission and reflection. Thus, you must divide your result by two in order to obtain the distance.

Distance = (0.034 cm/µs x 500 µs) / 2

Distance = 8.5 cm

The distance between the object and the sensor is now known to be 8.5 cm.

Wiring an HC-SR04 Sensor to an Arduino

We can begin connecting the HC-SR04 ultrasonic sensor to our Arduino now that we fully comprehend how it operates!

It is quite simple to connect the HC-SR04 to Arduino. Put the sensor on your breadboard first. Connect the ground pin of the Arduino to the ground pin of the VCC pin. Now join the trig and echo pins to the corresponding digital pins #9 and #10.

You ought to have something that resembles the example below after you’re finished.

Library Installation

It takes a lot of work to manually trigger the ultrasonic sensor and measure the pulse width of the received signal, but fortunately, there are several libraries at our disposal. The NewPing library is one of the most well-liked ones. We will utilize this library in our examples.

The NewPing library is very sophisticated. It may output measurements directly in centimeters, inches, or time periods and can simultaneously support up to 15 ultrasonic sensors.

You must first install this library since it is not a part of the Arduino IDE.

To install the library navigate to Sketch > Include Libraries > Manage Libraries… Allow the Library Manager to update the list of installed libraries and download the library index.

By entering “newping,” you can narrow your search. Select Install after clicking the first entry.

Arduino Example Code

Here is a straightforward sketch that takes advantage of the serial monitor to show a distance in centimeters. Try out this sketch before we begin a thorough investigation of it.

// Include NewPing Library
#include "NewPing.h"

// Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
#define TRIGGER_PIN 9
#define ECHO_PIN 10

// Maximum distance we want to ping for (in centimeters).
#define MAX_DISTANCE 400

// NewPing setup of pins and maximum distance.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print("Distance = ");
Serial.print(sonar.ping_cm());
Serial.println(" cm");
delay(500);
}

Open your serial monitor and set the baud rate to 9600 bps once the sketch has been uploaded. Try aiming the sensor at nearby objects that are lying about. The measured distance should start to stream soon.

Code Explanation:

The recently installed NewPing library is first incorporated into the sketch.

#include "NewPing.h"

The Trig and Echo pins of the HC-SR04 are connected to the defined Arduino pins first. Additionally, a constant called MAX DISTANCE has been defined. Pings sent beyond the specified maximum distance will be interpreted as “no ping clear.” Currently, MAX DISTANCE is set at 400 [default = 500cm].

#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400

Following that, a NewPing library instance named sonar is Made.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

We start the serial communication with the PC during setup.

void setup() {
Serial.begin(9600);
}

We use the ping_cm() method in the loop and print the outcome on the serial monitor. The distance in centimeters is returned once a ping is sent using this function.

void loop() {
Serial.print("Distance = ");
Serial.print(sonar.ping_cm());
Serial.println(" cm");
delay(500);
}

 

Other useful functions in NewPing Library

You can utilize a few helpful functions with the NewPing object.

The distance is displayed in centimeters. in the above sketch. Use the sonar.ping_in()  function if you want the result to be in inches.

Serial.print(sonar.ping_in());

The resolution of the aforementioned sketch is just one centimeter. Use NewPing in duration mode rather than distance mode to get the result in decimal form. This line needs to be changed:

Serial.print(sonar.ping_cm());

with below line

Serial.print((sonar.ping() / 2) * 0.0343);

To raise the accuracy of your HC-SR04, use the method ping median(iterations) in the NewPing library. This approach averages the remaining values after discarding out-of-range readings and taking many measurements as opposed to just one. It only takes five readings by default, but you can set any number.

int iterations = 5;

Serial.print((sonar.ping_median(iterations) / 2) * 0.0343);

Arduino Project – Contactless Distance Finder

Let’s quickly build a project to show how a basic ultrasonic sensor may be upgraded to a sophisticated contactless distance finder. In this project, a horizontal bar that shows the object’s distance from the user will be displayed on a 16 x 2 LCD Display.

Wiring

The connection to the LCD must then be made as illustrated below.

Library Installation

Before uploading the code and experimenting with the sensor, we must first install the LCDBarGraph library. This library will make it easier to draw a horizontal bar on the LCD, with the length of the bar serving as a representation of the object’s distance.

In order to install the library simply go to Sketch > Include Libraries > Manage Libraries… Allow the Library Manager to update the list of installed libraries and download the library index. You can narrow your search by entering “lcdbargraph.” Select Install after clicking the first entry.

Arduino Code

Try the sketch below once the library has been installed.

// includes the LiquidCrystal Library
#include <LiquidCrystal.h> 

// includes the LcdBarGraph Library
#include <LcdBarGraph.h>

// Maximum distance we want to ping for (in centimeters).
#define max_distance 200

// Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); 

LcdBarGraph lbg(&lcd, 16, 0, 1); // Creates an LCD Bargraph object.
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;

void setup() 
{
lcd.begin(16,2); // Initializes the interface to the LCD screen
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() 
{

// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the response from the HC-SR04 Echo Pin
duration = pulseIn(echoPin, HIGH);

// Determine distance from duration
// Use 343 metres per second as speed of sound
distance= duration*0.034/2;

// Prints "Distance: <value>" on the first line of the LCD
lcd.setCursor(0,0);
lcd.print("Distance: "); 
lcd.print(distance);
lcd.print(" cm");

// Draws bargraph on the second line of the LCD
lcd.setCursor(0,1);
lbg.drawValue(distance, max_distance);
delay(500);
}

 

This is how the result appears.

Code Explanation:

The Liquid Crystal Library must first be configured as usual. Next, use the LiquidCrystal instance you just made to construct a LcdBarGraph instance. LiquidCrystal should be referenced in the constructor of the LCDBarGraph.

LcdBarGraph’s constructor requires three additional parameters. The second is the LCD’s Character Column Number (in our case it is 16). The last two options allow you to arrange the bar anywhere you like.

// creating bargraph instance

LcdBarGraph lbg(&lcd, 16, 0, 1);

We use the drawValue(value, maxValue) function to display the bargraph after determining the sensor’s distance. With a value between 0 and maxValue, it creates a bar graph.

//display bargraph

lbg.drawValue(distance, max_distance);

Interfacing HC-SR04 with 3-Wire Mode

The 3-pin mode on your Arduino is useful if you only have a few digital I/O pins available. Two I/O pins are often required to connect an HC-SR04 sensor to an Arduino. However, in 3-wire mode, just one I/O pin is required as opposed to two.

A single I/O pin is used for input and output in this manner. Trig and Echo are not utilized simultaneously, therefore this is possible.

Here’s how to use the 3-wire mode to connect the HC-SR04 sensor to Arduino.

Simply attach the TRIG and ECHO pins to digital pin #9 and specify pin 9 for both pin values in the code. The remaining code is the same.

#define TRIGGER_PIN 9 // Trigger and Echo both on pin 9

#define ECHO_PIN 9

What are the limitations?

In terms of accuracy and general usage, the HC-SR04 ultrasonic sensor performs admirably, especially when compared to other inexpensive ultrasonic sensors. The HC-SR04 sensor may not always function as a result. The following images demonstrate a few of the drawbacks of HC-SR04’s -:

  • The sensor is farther away from the object or obstruction than 13 feet.
  • So that sound is not reflected back to the sensor, the object’s reflective surface is at a shallow angle.
  • Too little sound can be reflected by the item to reach the sensor. Additionally, sound may reflect off the floor if your device’s HC-SR04 sensor is set low.
  • The HC-SR04 sensor may have trouble detecting some things with soft, uneven surfaces because they absorb sound rather than reflect it (such as plush animals).

Leave a Reply

Your email address will not be published. Required fields are marked *

Index