Measuring distance with sound

Measuring distances from our robot to other objects, is one of the most common data we want to obtain. For example, if we are building an autonomous vehicle, we want to check it’s distance from obstacles to help it make the right decision about it’s course. There are also many more examples of robots that we want them to activate mechanisms when something or someone gets close to them.

One of the simplest, cheapest and most accurate ways to measure distances, is by using ultrasonic sensors. Their working principle is based on the fact that sound is reflected upon most objects and materials.

These sensors have a transmitter that sends a short ultrasonic burst and a receiver that senses the ultrasound upon it’s return. Knowing the speed of the sound in the air (approximately 343 m/sec), we can calculate the distance it traveled, if we measure the time passed for the ultrasound to return to the sensor.

Various ultrasonic sensors – 1: Sensor suitable for Arduino and Raspberry pi, 2: Sensor for MakeBlock, 3: Sensor for Lego EV3, 4: Sensor with transmitter and receiver in the same housing.

Working principle.

All ultrasonic sensors operate in a similar way. They send a short (a few microseconds long) ultrasonic burst from the transmitter and measure the time it takes for the sound to return to the receiver.

The ultrasound travels from the transmitter and when an obstacle comes in its way it bounces back and returns to the receiver.

Let’s say that it took 10 milliseconds for the ultrasound to return to the sensor. That means:

  • that the time in seconds is 0,01.
  • Knowing that sound travels in the air 343 meters for every second, we can calculate the distance in meters by simply multiplying seconds by 343. in our case 0,01 x 343 = 3,43 meters.
  • This is the distance that the ultrasound traveled to the obstacle and back to the sensor, so the obstacle is  3,43/2 = 1,715 meters away from the sensor.

Pros and Cons.

The main advantages of using ultrasonic sensors to measure distance are:

  • they are cheap and there is a plethora of choices in the market,
  • they are not affected by the color or the transparency of obstacles,
  • they are not affected by lighting conditions,
  • they are pretty accurate on their measurements.

Their drawbacks are:

  • They don’t work well enough on obstacles with small surfaces.
An object with a small surface facing the sensor is possible not to reflect the ultrasound well.
  • The angle of the surface of the obstacle is crucial for the sensor.
When the obstacle is facing the sound waves with an angle far from perpendicular the ultrasound can bounce off away from the sensor.
  • Obstacles made from sound absorbing materials (for example sponges) are hard to be traced by the sensor, since the absorb sound.

Choosing a sensor.

There is a wide variety of ultrasonic sensors on the market, for most robotics platforms. For those who prefer working with the Lego platform, EV3 and the older NXT, include ultrasonic sensors. Some examples of using them in the classroom are:

If you are an Arduino or Raspberry pi fan and want to dive more into how these sensors work, there are several options that you can find online. The most common and affordable choice is the HC-SR04, which costs less than a euro on ebay (August 2018). For more details and comparative tests with various ultrasonic sensors, i advise you to watch two detailed videos (here and here) from Andreas Spiess channel on Youtube.

The HC-SR04 ultrasonic sensor. The transmitter is on the left and the receiver on the right.

Connecting the sensor to Arduino and programming.

The HC-SR04 sensor has 4 pins:

  • VCC, that is connected to 5V,
  • GND, that is connected to Ground,
  • TRIG (Trigger), that is connected to the transmitter to send the ultrasonic burst,
  • ECHO, that is connected to the receiver.

There are two ways to connect the sensor to Arduino:

  • Connect TRIG and ECHO to different digital pins and make all the hard work and calculations in our program,
  • connect TRIG and ECHO to the same digital pin and use a library to make all the calculations.

I am going to start from the second way (easy) and then stay longer on the first, which gives the programmer more control and as an educator i find it more interesting.

One pin connection and the NewPing library.

The easy way. Connect TRIG and ECHO to the same digital pin, in this example pin 4.

For my program to work i will need to install the NewPing library to my Arduino IDE, using the library manager.

Just installed the NewPing library to Arduino IDE.

Now i can write a simple program to print the distance obtained by the sensor to the Serial monitor.

I uploaded the program to the board and started testing.

Test 1: Successful obstacle recognition at 25cm.
Test 2: Successful obstacle recognition at 15cm.
Test 3: Successful obstacle recognition at 2cm.
Test 4: Sensor fails to recognize object with small surface facing it at 10 cm and returns the distance from the wall.
Test 5: Sensor fails to recognize obstacle that is not faced perpendicular to sound waves and returns the distance from the wall.
Test 6: Sensor fails to recognize sponge at 25 cm. it returns a zero value, since the ultrasound is absorbed by the obstacle and nothing returns back.
Test 7: Even at 5 cm the sponge absorbs the ultrasound.

Two pin connection – Calculating distance from time.

As an educator, i find it more interesting to dig in the working principal of things, even if that means more work for my students. In order to do so in this example we will have to forget the luxury of the NewPing library and make all the calculations ourselves. First of all i changed the schematic by connecting the TRIG and ECHO to different digital pins.

Connecting TRIG to digital pin 4 and ECHO to digital pin 5.

Before i can start coding there are some things i need to clarify:

  • TRIG (Trigger) has a default LOW state and when we change it to HIGH it starts sending ultrasonic burst.
  • When ECHO receives the bouncing sound it returns a HIGH pulse to the Arduino.
  • I will use the pusleIn function to measure the time the ECHO pin stays in HIGH state. This functions returns time in microseconds.

Now i can start my algorithm:

  1. Set TRIG pin to HIGH.
  2. Wait for a short period of time (10 microseconds).
  3. Set TRIG pin to LOW. Now i have sent a short ultrasonic burst.
  4. Get the time from ECHO pin in microseconds.
  5. Convert microseconds to seconds (division by 1.000.000).
  6. Calculate the distance the sound traveled in meters. Multiply seconds by 343 m/sec.
  7. Now i have the distance i meters. I will convert it to centimeters by multiplying by 100.
  8. This is the distance the sound traveled to the obstacle and back. So the distance of the obstacle from the sensor is half of that. So i divide distance by 2.

I upload the program to my board and the sensor works as with the NewPing library, returning decimal values since all my variables are float.

Digging even further – Finding the actual speed of sound based on temperature and humidity.

So far i used the speed of sound to calculate distance from time, assuming that this is a constant value of 343 m/sec. That is not actually true. Speed of sound depends on the “density” of the mean it travels through. In solid materials the speed of sound is greater than liquids and in liquids sound travels faster than through gases.

The ultrasonic sensor sends sound through air which is a gas. In gases the speed of sound is affected mostly by the gas temperature, less by the gas humidity and even less by the gas pressure. For example in air with pressure of 1 Atm and

  • temperature of 0 degrees Celsius (32 F) and 50% humidity, the speed of sound is 331.61 m/sec,
  • temperature of 20 degrees Celsius (68 F) and 50% humidity, the speed of sound is 343.99 m/sec,
  • temperature of 30 degrees Celsius (86 F) and 50% humidity, the speed of sounds is 350,31 m/sec και
  • temperature of 30 degrees Celsius (86 F) and 90% humidity, the speed of sound is 351,24 m/sec.

There are many online calculators for the speed of sound. I used the one on to get the above results.

Since i had a cheap temperature – humidity sensor lying around (DHT11 Temperature and Humidity Sensor), i decided to improve the calculations in my code, using these two values to estimate a more accurate speed of sound value.

First of all i embedded the new sensor in my schematic. Typical DHT11 sensors have either 3 pins (5V, GND and Signal) or 4 pins (5V, GND, Signal and NULL). The connections  are as follows:

  • 5V DHT11 –> 5V Arduino
  • GND DHT11 –> GND Arduino
  • SIGNAL DHT11 –> A0 pin Arduino
Adding the DHT11 to the schematic.

The next step was to add the measurement of temperature and humidity in my code using the dht.h library, which you can download from here. I followed the step by step tutorial from Brainy Bits and now the only thing i needed was to calculate the actual speed of sound.

After a long search, i found that the formula needed was originally published in 1993 by Owen Cramer in his work “The variation of the specific heat ratio and the speed of sound in air with temperature, pressure, humidity, and CO2 concentration.”. I was also happy to find a JAVA implementation by a  research team from the Univeristy of Sao Paolo Brazil. With a few tweaks to adjust it to my code the full program is as follows:

I uploaded the program to my board and starting testing. I was happy to have more accurate measurements, even if that does not play a significant role in small distances of few cm.

Every 2 seconds the program calculates the obstacle distance using temperature and humidity to calculate an accurate speed of sound.

Using the ultrasonic sensor in class.

The use of ultrasonic sensors in educational robotics is very common and there are hundreds of examples over the internet, either using the Lego platform or Arduino and Raspberry pi. Recently tinkercad added a new command block for getting the distance from an ultrasonic sensor.

Our program in Tinkercad with just 3 blocks.

I find particularly interesting, for educational purposes, the analytical way of calculating the distance, from the time the sound takes to travel to the obstacle and back.

In a previous project (smart trash can), that we implemented with my students from the evening club Young Hackers, we spent a lot of time to fully understand the algorithm that calculates distance from time using an analytical worksheet (in greek). We implemented the algorithm using a block style language (Ardublockly) that helped students a lot to understand every step of the way.

Using Ardublockly to implement the Algorithm.

1 Comment