Using an Ultrasonic Distance Sensor With Arduino

In this tutorial we will be looking at how to use an Ultrasonic Sensor to measure distance using an Arduino. This type of sensor emits a burst of ultrasonic sound and then waits to hear the echo. These sensors are generally inexpensive, fairly accurate, and not affected by lighting conditions like infrared based systems. We will be looking at three sensors, these are all code compatible but require subtle changes in the wiring due to differing pinouts.

A Few Considerations:
Before we jump into getting this sensor hooked up there are a few points to consider when using it in a project.

• If there is any chance of these coming in contact with water, the weatherproof version must be used.
• The further an object is away, the larger it needs to be to have reliable detection.

How It Works:
The sensor itself takes care of most of the heavy lifting and as a result, there is one input (Trigger) and one output (Echo). When the trigger is set high, an ultrasonic burst is sent and the circuit internal to the sensor starts watching for a response. When the response is received, the echo pin is immediately triggered high. We can simply time how long it takes from trigger to echo and divide by two. Since sound travels at a reasonably consistent speed, the distance is easy to obtain.

The Parts Needed:

This tutorial will be requiring a few common parts:

We have also used one of our half sized Arduino Mounting Plates in this tutorial. The mounting plate keeps your Arduino and breadboard neatly fixed next to one another, allowing for much more organized prototyping!

flow-2

The Schematic

This handy little diagram shows how we will be connecting everything. Depending on the sensor, the pinout may vary slightly. Don’t worry if it looks a little overwhelming, we will be going through this step by step!

sketch1

Step 1 – Wire Up The Sensor

These sensors typically have breadboard compatible pins so we can simply insert it into the breadboard as shown. While the pin layout of each sensor will vary, the pins are labeled directly on the board – so hookup is a breeze. VCC will go to our 5V rail on the breadboard, GND will go to the Ground rail. We will run TRIG directly to digital pin 2 on the Arduino and run ECHO directly to digital pin 3.

Note: If you are using the HY-SRF05, there is an extra “OUT” pin in the header. This pin can simply be left disconnected.

Note: If you don’t have a breadboard, you can just as easily connect this sensor directly to the Arduino pins as well. Just use our Premium Female/Male Jumper Wires to connect them instead.

flow-5

Step 2 – Double Check And Plug It In!

Before we give the Arduino power it is always a good idea to go over all of the connections to make sure there are no wires in the wrong spot – sometimes that can make for a very expensive mistake!

One way to avoid this problem is good wire color discipline. In other words, decide on a purpose for each color of wire and stick to them! In this example all 5V power are red wires, all grounds are black wires, and green / blue / ect. are signal wires. This way, if you ever see a red wire going to a black wire you will know right away that something isn’t quite right!

flow-2
1
2
3
4
5
6
7
8
9
void setup() {
  // put your setup code here, to run once:
}
void loop() {
  // put your main code here, to run repeatedly:
}

Step 3 – Starting The Code

Now that we have finished with the hookup we need to start writing some code. We will be using the Arduino IDE, this is available from https://www.arduino.cc/en/Main/Software

We will start with the “BareMinimum” sketch found by clicking “File” and selecting Examples / Basic / BareMinimum. This sketch is a great starting point as it includes the Setup and Loop functions – we will write the rest!

Step 4 – Understanding How To Read The Sensor

We know that if we set the trigger pin high an ultrasonic burst will be sent, and once the echo is detected, the echo pin will be triggered high. So this is really just a matter of timing how long it takes the sound to bounce back and dividing by two. We can then use that to figure out the distance by dividing by the speed of sound.

There are a lot of different ways this could be accomplished – in this case we will use the PulseIn function as it is relatively simple. This is normally used to measure frequency, but since the receiver will “hear” the output twice (initially when it is sent, and the echo off the objec) we can use this to count the time between send and receive.

Step 5 – Starting The Code

We are starting with the BareMinimum Sketch found in the IDE, it should look something like this:

1
2
3
4
5
6
7
8
9
void setup() {
  // put your setup code here, to run once:
}
void loop() {
  // put your main code here, to run repeatedly:
}

The Setup section is used for anything that needs to be done once when the Arduino starts. The Loop section will be run over and over again in a loop.

Step 6 – Define Constants

We are going to start by defining what pin we are going to use for our trigger and echo. These are the pins on the Arduino that you have connected the TRIG and ECHO pins on the sensor. We then configure the TRIG pin as an output and the ECHO as an input. A good way to remember how this works: When ever you are “telling” a piece of electronics to do something using the Arduino it will be an OUTPUT; if you are “listening” to something, it would be an INPUT.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Define our pins
#define TRIG 2
#define ECHO 3
void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT); 
}
void loop() {
  // put your main code here, to run repeatedly:
}
  • (2) Define the Trigger Pin
  • (3) Define the Echo Pin
  • (7) Configure Trigger as an Output (to send a signal)
  • (8) Configure Echo as an Input (to receive a signal)

Step 7 – Setup Serial

We need some way to display the sensor data – in this case the Serial Monitor built into the Arduino IDE is probably the easiest. The serial monitor allows data collected or calculated by the Arduino to be displayed on the computer you are programming the Arduino from. The serial connection is configured in the Setup function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Define our pins
#define TRIG 2
#define ECHO 3
void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600); 
}
void loop() {
  // put your main code here, to run repeatedly:
}
  • (9) Enable the Serial Port at 9600 baud

Step 8 – Triggering The Sensor

The first step in measuring a distance is triggering the sensor to send the ultrasonic pulse. This is done by setting the TRIG pin HIGH for 10 microseconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Define our pins
#define TRIG 2
#define ECHO 3
void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600); 
}
void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(TRIG, HIGH);//Set TRIG pin HIGH
  delayMicroseconds(10);   //Pause 10 microseconds
  digitalWrite(TRIG, LOW); //Set TRIG pin LOW
}
  • (14) Set the trigger pin HIGH
  • (15) Wait 10 microseconds before shutting the pin off
  • (16) Set the trigger pin LOW

Step 9 – Listening For The Echo

Next we will listen for the echo – this means we need to use the PulseIn function with our ECHO pin. Since the sensor outputs a HIGH signal when triggered, we will be looking to count time between HIGH pulses.

The PulseIn function returns a time in microseconds, and since sound travels at approximately 29cm / microsecond, we can figure out a distance. The distance returned would be the distance the sound traveled (to the object and back), so we will have to also divide the distance by two: returnTime / 29 / 2 (or returnTime / 58 to simplify it)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Define our pins
#define TRIG 2
#define ECHO 3
void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600); 
}
void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(TRIG, HIGH);//Set TRIG pin HIGH
  delayMicroseconds(10);   //Pause 10 microseconds
  digitalWrite(TRIG, LOW); //Set TRIG pin LOW
  float distance = pulseIn(ECHO, HIGH); //ECHO Pin, Looking for a HIGH signal
  distance = distance / 58;  //Time in microseconds divided by twice the distance sound travels per microsecond (cm)
}
  • (18) Run the PulseIn function and store the collected data in a new variable “distance”
  • (19) Divide the result by 58 to get the distance in centimeters

Step 10 – Print The Results

Finally, we will want to see the results. To do this, we will print the value to the serial monitor. We will also add a small delay so we aren’t overloaded with information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Define our pins
#define TRIG 2
#define ECHO 3
void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  Serial.begin(9600); 
}
void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(TRIG, HIGH);//Set TRIG pin HIGH
  delayMicroseconds(10);   //Pause 10 microseconds
  digitalWrite(TRIG, LOW); //Set TRIG pin LOW
  float distance = pulseIn(ECHO, HIGH); //ECHO Pin, Looking for a HIGH signal
  distance = distance / 58;  //Time in microseconds divided by twice the distance sound travels per microsecond (cm)
  Serial.print(distance); //Print the distance
  Serial.println(" cm");  //Print the unit of measure
  delay(500);             //Delay for half a second
}
  • (21) Print the distance to the Serial Monitor
  • (22) Print the unit of measure to the Serial Monitor and terminate the line
  • (23) Wait half a second so we aren’t measuring constantly

Step 11 – Upload The Code And Test

Now that all of the code has been written it can be uploaded to your Arduino! Click “Upload” button in the top left corner of the Arduino IDE and it should upload without any issues. Next, click the “Serial Monitor” button in the top right corner (it looks like a magnifying glass). After a few seconds you should start to see a stream of data appear in the window – that is your distance in centimeters.

finalcode1