Electronics Software Development

Interfacing Ultrasonic Distance Sensors With An Arduino Uno

Ultrasonic Distance Sensors And Arduino Graphic
Written by John Woolsey

Skill Level: Intermediate

Table Of Contents

Introduction

This tutorial will teach you how to interface HC-SR04, and compatible, ultrasonic distance sensors with an Arduino Uno. A basic understanding of electronics and programming is expected along with some familiarity with the Arduino platform. If you are new to Arduino or would just like to refresh your knowledge, please see our Blink: Making An LED Blink On An Arduino Uno tutorial before proceeding with this one.

The resources created for this tutorial are available on GitHub for your reference.

This tutorial only demonstrates the basic configuration and reading of an HC-SR04, or compatible, ultrasonic distance sensor. An enhanced version that separates out the ultrasonic distance sensor as a distinct class, incorporates multiple sensors as an array, and provides other additional enhancements is provided in the GitHub repository.

What Is Needed

Background Information

Distance sensors come in a variety of types and form factors for use in a wide range applications. They differ greatly in the range of distances they detect and the resolution of the distances measured. SparkFun provides a good overview of these differences in their Distance Sensing guide that also contains a link to their Distance Sensor Comparison Guide that provides many technical specifications for the different types of distance sensors available.

This tutorial will focus on the HC-SR04, or compatible, ultrasonic distance sensor. It is a very popular and inexpensive sensor used in small to medium range applications such as general distance measurement, proximity detection, and robotics. The HC-SR04 requires a 5 V supply, consumes 15 mA during reads, and can read distances between 2 and 400 cm. Specifically, I will be using the compatible RCWL-1601 sensor since it allows for 3-5 V operation, uses less current (2.2 mA), and provides a little longer range (2-450 cm) than the HC-SR04.

My development system consists of the Arduino Uno WiFi Rev2 development board connected to a macOS based computer running the desktop Arduino IDE. If you are using a different Arduino board or computer setup, the vast majority of this tutorial should still apply, however, some minor changes may be necessary.

If you need assistance with your particular setup, post a question in the comments section below and I, or someone else, can try to help you.

Building The Circuit

Before connecting any circuitry to your Arduino board, disconnect it from power and your computer. This avoids accidental damage during wiring.

Each HC-SR04 sensor will use two digital pins on your Arduino, for Trigger (output) and Echo (input), along with power and ground connections. Connect the sensor’s Gnd and Vcc pins to your Arduino’s GND and 5V pins respectively. Then connect digital pins D2 and D3 on your Arduino to the sensor’s Trig and Echo pins respectively.

Once the circuit is built, you can connect your Arduino to your computer with the USB cable.

Writing The Software

Open the Arduino IDE and create a sketch named HCSR04_Simple.

The first thing we will do is add a #define statement at the beginning of the sketch

#define DEBUG 1

that will allow us to optionally print debugging information to the Serial Monitor.

Next, add the global variables for the distance sensor’s pin mapping.

const byte DistTrigger = 2;
const byte DistEcho = 3;

Before we can use our sensor, we need to configure it for use. Update the setup() function to include the relevant pin modes along with enabling printing to the Serial Monitor. We will also add a small delay to give the sensor time to initialize.

void setup() {
   if (DEBUG) {
      Serial.begin(9600);
      while (!Serial);
   }
   pinMode(DistTrigger, OUTPUT);
   pinMode(DistEcho, INPUT);
   delay(100);
}

Now that our sensor is configured, we need to read it. To initiate a read on this particular type of sensor, the Trigger pin needs to be held at a high logic level for a minimum of 10 microseconds (µs). The transmitter on the sensor will then send a burst of eight pulses of ultrasound at 40 kilohertz (KHz) and the sensor’s Echo pin will immediately go high. The Echo pin will stay high until the reflected sound is detected back at the receiver. The distance between an object and the sensor can be calculated based on the time the Echo pin stays at this high level. Since the sound has to travel to the object and back to the sensor, we also need to divide by two.

Distance = Pulse Duration * Speed Of Sound / 2

The speed of sound at ground level in dry air is typically around 343 meters per second (m/s) and depends on temperature and the medium it is traveling through.

Create the readDistanceSensor() function and place it at the end of the sketch.

float readDistanceSensor() {
   digitalWrite(DistTrigger, LOW);
   delayMicroseconds(2);
   digitalWrite(DistTrigger, HIGH);
   delayMicroseconds(10);
   digitalWrite(DistTrigger, LOW);

   float duration = pulseIn(DistEcho, HIGH);  // in microseconds

   float distance = duration * 0.0343 / 2.0;  // in centimeters

   return distance;
}

The first part of the function (lines 2-6) go through the process of initiating the 10 µs pulse on the sensor’s Trigger pin.

Line 8 uses the Arduino pulseIn() function to record the length of the pulse, in microseconds, received from the Echo pin. Since the duration of the Echo pulse is retrieved in microseconds and we want the distance in centimeters, our distance equation becomes the following

Distance (cm) = Pulse Duration (µs) * 0.0343 (cm/µs) / 2

and is implemented on line 10.

Finally, let’s update the loop() function

void loop() {
   float distance = readDistanceSensor();
   if (DEBUG) {
      Serial.print("Distance sensor read "); Serial.print(distance);
      Serial.println(" cm.");
   }
   delay(1000);
}

to read the distance sensor once each second. The DEBUG compound statement will display our readings in the Serial Monitor if enabled.

Running And Testing The System

Now that our circuit is built and our software is written, it is time to run and test our project.

Open the Serial Monitor window (Main Menu > Tools > Serial Monitor) so that we can see the program’s output. Upload the sketch to the board and you should see something like the following.

Distance sensor read 138.42 cm.
Distance sensor read 139.40 cm.

Place your hand or another object at varying distances from the sensor and watch the distances being reported. If you grab a ruler, you can even test the accuracy of your sensor. The resolution and accuracy for the HC-SR04 are both rated at 3 mm. That is very good for an inexpensive distance sensor.

Adafruit, where I obtained my sensors, states on their product pages that although the distance sensors work across their rated ranges, the best results are achieved in the 10-250 cm range.

In addition, I found during testing that distance measurement times were typically below 10 ms when using the pulseIn() function, but can take up to 50 ms for large distances. When the sensors are disconnected, the pulseIn() function can take up to a second to time out.

That covers the basics for connecting ultrasonic distance sensors to your Arduino Uno.

Summary

In this tutorial, we learned how to connect, configure, and read HC-SR04, and compatible, ultrasonic distance sensors using an Arduino Uno. We also learned some of the basics of how these sensors work. They can be a valuable component to add to your electronics toolbox.

The final commented source code used for this tutorial, HCSR04_Simple, is available on GitHub.

If you are interested in additional capabilities, like reading multiple distance sensors in order for your robot to avoid objects, check out my enhanced sketch in the same GitHub repository. It is named HCSR04_ClassArray and implements the following:

  • separates out the distance sensor as a distinct class,
  • provides the ability to specify a valid distance range,
  • incorporates an array of sensors,
  • provides the ability to specify the sensor sampling rate,
  • provides distance sensor measurement times for use during testing, and
  • adds enhanced functionality.

If there is something that needs further explanation, please let me know in the comment section and I will try to answer your question.

Thank you for joining me in this journey and I hope you enjoyed the experience.

About the author

John Woolsey

John is an electrical engineer who loves science, math, and technology and teaching it to others even more.
 
He knew he wanted to work with electronics from an early age, building his first robot when he was in 8th grade. His first computer was a Timex/Sinclair 2068 followed by the Tandy 1000 TL (aka really old stuff).
 
He put himself through college (The University of Texas at Austin) by working at Motorola where he worked for many years afterward in the Semiconductor Products Sector in Research and Development.
 
John started developing mobile app software in 2010 for himself and for other companies. He has also taught programming to kids for summer school and enjoyed years of judging kids science projects at the Austin Energy Regional Science Festival.
 
Electronics, software, and teaching all culminate in his new venture to learn, make, and teach others via the Woolsey Workshop website.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.