Download PDF Parts List View on YouTube Download Code

Today we’re having a contest of sorts, a match between two popular types of distance sensors. Get ready to place your bets on the winner!

I’ve got a bit of a different type of experiment going on in the workshop today, it’s a battle between two types of distance sensors. One of them uses lasers and is extremely small, and the other is our old friend the HC-SR04 which chirps out ultrasonic sound waves.

We’ll compare the performance of these sensors in the special DroneBot Workshop Distance Tester, constructed especially for this article and video! 

HC-SR04 vs TOF10120

We’ll compare both devices for accuracy in the 10 – 100 cm range, against both reflective and absorbent surfaces.  We’ll also compare the spec sheets to see where each sensor shines.

Come and get a good seat for the match and we’ll get started!

Distance Sensing

Distance Sensing is a common and even critical function in many modern designs. It’s used extensively in robotics but also finds use in a variety of different applications such as security sensors, process control designs, quadcopters, and vehicle safety systems.  It even finds a home in hands-free bathroom fixtures.

We have discussed these types of sensors before, including an extensive article about using the popular HC-SR04 ultrasonic distance sensor.

All of these types of sensors use the same basic principle, they just execute it differently:

  • A signal is transmitted at the target from the sensor. 
  • The target reflects the signal back to the sensor.
  • The sensor receives the reflected signal.
  • The time delay between the sending of the signal and its reception is used to calculate the distance to the target.

The HC-SR04 used ultrasonic sound at a frequency of about 40 kHz, too high for us humans to hear but potentially audible to some animals. Fifi and Fido beware!

Sound is only one of many different mediums that you can use to do this trick. The most well-known application of this principle is RADAR, which uses microwaves.

Light is also a popular method of building a distance sensor. We have already seen this used in a very advanced way when we discussed using LiDAR a while back.  

Light sensors have several advantages over their ultrasonic counterparts. They can be made very small and can be waterproof. And because the speed of light is so much quicker than sound, light sensors can respond very quickly and can be queried more often.

But light sensors also require advanced electronics, capable of measuring the incredibly small time differences encountered when working with light.  Consider this:

  • In one second sound will travel 343 meters (0.343 Km), a little longer than three American football fields placed end-to-end.
  • In one second light will travel  299,792,458 meters (299,792.458 Km), about three quarters the distance from the Earth to the Moon.

Advanced light sensors make use of lasers, combine that with the high-speed electronics and the cost of light sensors can be substantially higher than ultrasonic sensors.

Ultrasonic sensors also have some advantages over light sensors. Not only are they lower in cost, they generally have longer measurement ranges, at least in low-cost sensors.

Each type has advantages and disadvantages in different environments, and both can be subject to external interference.

In robotics, it is common to use both types to get the advantages of each type of sensor.

Our Contestants – HC-SR04 vs. TOF10120

It’s time now to meet today’s contestants – yes that did sound a bit like a game show host speaking, didn’t it? 

We have our old friend the HC-SR04 Ultrasonic Sensor pitted up against the newcomer, a TOF10120 Laser range finder. This new guy is being offered on all the usual channels (Amazon, eBay, etc) and is very, very tiny.

Testing Parameters

I’m not expecting any real winners or losers today, as each sensor has its strengths and weaknesses. Here is what we’ll be comparing:

  • Cost – How expensive is the device?
  • Interface – How does the sensor connect up to your microcontroller?
  • Size & Weight – How large is the sensor, how much does it weigh?
  • Current – How much current does the sensor consume?
  • Maximum Rated Range – What is the maximum range the sensor can detect?
  • Minimum Rated Range – What is the minimum range the sensor can detect?
  • Range Test – A test of the sensor at 5 preset distances, each with two different target surfaces.  How accurate are they?

Let’s take a closer look at the two sensors.

HC-SR04

The HC-SR04 is a very popular ultrasonic distance sensor. It is widely available and is a staple of low-cost collision-avoidance robots.

HC-SR04 features

This is a very versatile sensor, I have done a complete article and video devoted solely to the HC-SR04 as it is such an important component.  If you want to bring yourself up to speed on the HC-SR04, then that article is a great place to start.

HC-SR04 Pinouts

The HC-SR04 is pretty simple to use. It has four pins:

  • VCC – Power, +5 VDC
  • Trig – the Trigger input, the input that you use to initiate a measurement. Each time you input a pulse of at least 10ms the sensor sends eight sets of 40 kHz pulses.
  • Echo – The received pulse. It stays HIGH while the sensor waits for returned reflection data.
  • GND – Ground

You can tie the Trigger and Echo pins together and use the sensor in “3-wire mode” to save on an I/O pin.

The HC-SR04 has a rated range of 2-400 cm.

TOF10120

The TOF10120 is a Laser “time of flight” sensor that uses VCSEL (Vertical-Cavity Surface-Emitting Laser) technology to measure distance.  It is a very tiny device, measuring only 20 * 13 * 5 mm.

TOF10120 features

This device has a multitude of uses, including in those appliances like hand dryers and automatic sinks which use the sensor to detect movement.

This device communicates over I2C, it also has a serial connection.

The TOF10120 comes complete with an interface cable for use during experiments. It brings out the 6 pins on the sensor. The cable is color-coded as follows:

TOF10120 Pinouts - Color Coded

The device operates on voltages between 3 and 5-volts, so it is suitable for use with 3.3-volt logic.  It has a stated range of 10 – 180 cm.

Comparing the two Devices

As these devices use different technologies (sound vs. light) to achieve their goals they each have specific advantages and disadvantages. Here are a few things to consider when choosing which one to use:

HC-SR04 - TOF10120 Compared

  • The HC-SR04 is less expensive you can buy several of them for the price of one TOF10120.
  • The TOF10120 is a sealed unit and is ideal for applications where moisture or dirt may be present.
  • The TOF10120 is much smaller than the HC-SR04.
  • As light travels much faster than sound the TOF10120 responds much quicker than the HC-SR04.
  • The HC-SR054 has a wider field of view, which may or may not be a disadvantage, depending upon your application.
  • The TOF10120 can be used with 3.3-volt or 5-volt logic. The HC-SR04 can only be used with 5-volt logic.
  • Currently, there is very little English documentation for the TOF10120.

Having said all that, either unit would be a good choice for many common applications. 

TOF10120 vs HC-SR04 size comparison

Sensor Test Sketches

To run our tests, we will need a sketch for each of the sensors.  Nothing fancy, just something that will read the sensor and report the reading on the serial monitor will be sufficient.

So before we move to the testbed we will first hook up our two sensors and check them out with a simple sketch.

HC-SR04 Hookup

I’m going to use one of the experiments I performed in the article and video I made about the HC-SR04 as my test sketch for the ultrasonic sensor. And I’m going to add an additional component as well.

HC-SR04, DHT-22 and Arduino Hookup

The extra part is a DHT-22 temperature and humidity sensor. I’m adding this because the speed of sound is influenced by environmental factors like temperature and humidity, so I wanted to factor that in when calculating distance. 

I’m running the HC-SR04 in a 4-wire mode in this hookup.

HC-SR04 Code

This sketch is an old one from early 2017, however, it serves its purpose.

The sketch requires three libraries, as the Adafruit DHT Library is dependent upon the Adafruit Universal Sensor Library. Both libraries can be installed using your Arduino IDE Library Manager.

You’ll also need to install the NewPing Library, again you can install this by searching for it in the Library Manager.

The sketch is pretty simple, if you’d like a detailed explanation of it please see the original article about using the HC-SR04.

Most of the action in the sketch goes on in the Loop. The first thing that occurs here is the temperature and humidity are read from the DHT-22. These are then used to calculate the speed of sound in centimeters per millisecond, factoring in temperature and humidity.

This value is applied to the HC-SR04 time delay reading, which is then divided in half to determine the distance.

You’ll note that there are a couple of time delays applied to the readings, to allow both the DHT-22 and HC-SR04 to stabilize between readings.  This adds up to a total delay of about 2.5 seconds, so that’s how often we can expect a reading.

The results of the distance equation, as well as the temperature and humidity readings, are displayed on the serial monitor.

HC-SR04 Quick Check

So let’s give the ultrasonic sensor a quick test.

HC-SR04 Basic Test

Hook up everything as shown in the diagram and load the sketch, being sure to remember to install the three libraries first.  Then use a test object as a target, I used a notepad when I did this.

The resulting readings seemed reasonable, so I’ll consider our HC-SR04 to be working properly.

TOF10120 Hookup

Hooking up the TOF10120 is very simple, thanks to the cable provided with the unit. As the cable uses female Dupont pins I just used small jumper wires to connect it directly to my Arduino.

TOF10120 Arduino hookup

As we are using the I2C connection there are only four connections to the Arduino – power, ground, SDA, and SCL.  I did not use pull-up resistors and everything seemed to work correctly.

There are two other connections to the sensor serial port that are left unconnected in this experiment.

TOF10120 Code

One difficulty in working with the TOF10120 is a lack of documentation. While there is a wealth of documentation, app notes and sample code for the HC-SR04 there is very little available for the TOF10120, at least in English. 

The following code came from a YouTube user named “SurtrTech” who claims he/she obtained it from a Chinese website. Unfortunately, no link to the actual source was provided, so I can’t credit the original author.

The sketch doesn’t require any additional libraries, the only library it uses is the Arduino Wire Library which simplifies using I2C.

The real action in this sketch occurs in the SensorRead function. If you step through this function you’ll see how the I2C bus is used to contact the sensor, request a reading and add the result to a data buffer.

Another function, ReadDistance, calls the SensorRead function every time it wants a reading. It then takes the value off the buffer, delays 300 ms and then outputs it as in integer. The integer will be the distance in millimeters.

The Loop just calls ReadDistance and prints the value to the serial monitor.

TOF10120 Quick Check

After wiring up the TOF10120 and loading the sketch I tested everything out, again using a notepad as a target.

TOF10120 Basic Test

The device responded quickly every time I moved my target, so it looks like it’s working.

Note the two unconnected wires from the sensor, these are for the serial I/O port. 

Performance Tests

Now that we have our two distance sensors working it’s time to get to the actual competition!

Ideally, to do this test properly, I would have used a large room with controlled temperature, humidity and light levels. Unfortunately, that isn’t feasible, so I did the tests on my workbench.  It is certainly not as scientific, but it does represent more of a “real world” situation.

DroneBot Workshop Distance Testbed

To conduct these tests I created the “DroneBot Workshop Distance Testbed”, which is an eloquent name for some scrap wood from the workshop!

The testbed consists of a 4-foot long piece of particle board that has several wood spacers glued to it. These spacers are made to hold a reflector block in several pre-measured positions.

The reflector block itself is a piece of wood with two different surfaces. On one side there is a small piece of plywood, which provides a smooth surface. On the other side, I affixed a piece of foam, the same thickness as the plywood. This provides an absorbent irregular surface.

The sensors and the Arduino Uno driving them are placed on an elevated surface at the “zero-point” of the testbed. The surface is elevated so that the bottom board itself doesn’t interfere with the sensors.

Testing Sequence

To keep things at an even playing field, I’m going to calibrate each sensor at the 25 cm mark with the reflective (plywood) surface. Then we will test the sensors in all the remaining positions, with both the plywood and foam sides.

The preset positions are as follows:

  • 10 cm
  • 25 cm
  • 50 cm
  • 75 cm
  • 100 cm (1 meter)

I’m limited to a one-meter test due to the size of my workbench!

So let’s see how the two sensors performed.

HC-SR04

The ultrasonic sensor performed surprisingly well, although I did add the DHT-22 temperature and humidity sensor to help improve its performance.

After calibrating the sensor at 25 cm I tested it at 10 cm and 50 cm. Both readings were well within a centimeter accuracy, which is pretty good for a cheap sensor.

HC-SR04 distance-test

After trying to move past 50 cm, however, I experienced problems. I know from previous experience that the sensor is capable of much greater distances than that, but on my testbed, I couldn’t get much past the 50 cm mark.  So all of the reading above that were pretty well meaningless.

What I expect is happening is that the sensor is triggering on something besides the testbed on my workbench. This sensor has a pretty wide field of view, and so it is likely hitting on either the parts cabinets or myself. After moving out of the way without any effect on the readings I’m blaming the parts cabinets!

Things got more interesting when I tried the foam side of the reflector. 

As I had suspected, the sound waves don’t reflect off of the foam. Instead, they are bouncing off the surface of the wooden block, passing through the foam as if it wasn’t there.

As a result, the tests at 10, 25 and 50 cm were almost a centimeter off. Both my plywood and foam are a quarter-inch thick, which is about a sixth of a centimeter, and that seemed to account for the difference.

As I knew that the tests after 50 cm were pointless I didn’t bother to record them.

What impresses me about this sensor is that it performed really well until I ran into the interference issue.  When you consider it’s price it’s no wonder it’s such a popular device.

TOF10120

The Laser time-of-flight sensor has a range of 10 cm to 180 cm, so I was curious how it would perform at the 10 cm mark.  It has millimeter accuracy so 10 cm is 100 mm, and it came within 5 mm of the mark. 

The sensor also did very well at the 50 cm mark.

TOF10120 distance test

But on the higher points, 75 and 100 centimeters, the readings were off by a great deal, over 10%.

The documentation that I was able to obtain for the sensor claims that the range and accuracy are affected by many factors, including ambient light and the reflectivity of the surface being detected. 

So I tried the experiments with the lights out and with a white (and black) sheet of paper over the plywood. Neither seems to change the results.

One of the more interesting results was what happened when I used the foam side.

I had expected that the sensor might get fooled by the foam and give erratic readings. But the readings were pretty steady, but they were all out by the same factor – the thickness of the foam.

TOF10120 looking through foam

It seems the laser beam passed right through the foam and hit the underlying board. Just as the ultrasonic sound waves did.  I hadn’t expected that.

Perhaps my foam is “invisible” in infrared light?

One thing that can’t help but impress you when using this sensor is how fast the data gets updated.  It really would be great for moving objects, like robots, quadcopters and model boats.

Conclusion

Both sensors performed well in the 10 – 50 cm range, and both of them were affected by the foam side of the test target.

The ultrasonic sensor readings above 50 cm were meaningless, probably due to external interference from my workbench. 

The laser sensor accuracy after 50 cm really dropped, although since my next test point was at 75 cm I ‘m not certain exactly where the drop was.

When factoring in the cost difference the HC-SR04 is a clear winner, providing that you don’t require very fast readings or an environmentally-sealed sensor. But you also need to remember that I use dan DHT-22 temperature and humidity sensor in my circuit. If you add in the DHT-22 cost the two sensors come out to be within a couple of dollars of each other.

The high data rate of the TOF10120 is impressive, and I know I’ll be making use of one in a robotics project soon.

In fact, I think an even better idea is to build a detector that uses both of these sensors, gaining the advantages of each one. I’ll get to work on that right now!

 

Parts List

Here are some components that you might need to complete the experiments in this article. Please note that some of these links may be affiliate links, and the DroneBot Workshop may receive a commission on your purchases. This does not increase the cost to you and is a method of supporting this ad-free website.

COMING SOON!

 

Resources

Code for this Article – All the code used in this article in a handy ZIP file.

PDF Version – A PDF version of this article, great for printing and using on your workbench.

 

LASER vs Ultrasonic – Distance Sensor Tests
Summary
LASER vs Ultrasonic - Distance Sensor Tests
Article Name
LASER vs Ultrasonic - Distance Sensor Tests
Description
We will test the HC-SR04 ultrasonic range finder and the TOF10120 time of flight Laser sensor to see which is the most accurate.
Author
Publisher Name
Dronebot Workshop
Publisher Logo
Subscribe
Notify of

24 Comments
Oldest
Newest
Inline Feedbacks
View all comments
egers
4 years ago

Great article! How would you use both of the sensors in one project? can you give me an example of the code yoou would use? Thanks.

mike
4 years ago

Be interesting to see the ir spread from the TOF10120. If you turn the lights out maybe it will show. You can also pick up ir film that will glow. A tube to isolate narrow the beam (assuming it spreading). As for readings they seem to be consistent so you could map them out in software.

Feral Ace
1 year ago
Reply to  mike

I think you could try just testing out the spread by using a small target and moving it from side to side until it no longer registers. This will be different from the beam’s actual full beam but it will show you the measuring cone. I’ll be getting some of these very soon so I’ll try it, but by the time I get round to it I’ll have forgotten I posted this here! I suspect though that the beam is fairly narrow and maybe not really relevant at these distances as it’s a laser so in all practical terms it’s… Read more »

PhilW
4 years ago

Useful video and excellent website. Any thoughts about using the code for TOF10120 on a Nano or ESP?

AndyK
4 years ago

Saw this very interesting comparison – and found some specs on a Korean shopping website for the TOF (translated from Korean with the BING-translator). Especially interesting I find that there is only a value for the indoor accuracy. As the accuracy is a rather large 5% it of course explains the increasing differences you measured with increasing distances. And an inaccuracy that is increasing with distance and can be 9cm off for the max – I guess everyone has to decide on their own if that is acceptable for their particular use case. The time of the flight range sensor… Read more »

Feral Ace
1 year ago
Reply to  AndyK

If there is an error, it depends if it’s a consistent error or dependent on other factors. If it’s a consistent error, it shpould be easy to use a look up table to linearise the error. If however it’s random, I wonder if averaging a certain number of readings (given that it’s so fast per reading) will increase the accuracy? It will be easy to test whether it’s the first of the second just by taking repeated readings and seeing what happens. Also, what variances there are with different surfaces.

Joe
4 years ago

Great write-up. Thanks for doing that!
Do you think it is possible to display the output of the TOF10120 with micron resolution, instead of mm resolution? I would be curious to see the accuracy/repeatability of measurement within a measurement range of <1mm.

4 years ago

Thanks so much for all of your informative videos and website. Just thought you should know that there’s a chunk of code in the TOF sketch that does nothing. I suspect it was there so that the original author could use printf(). You can safely remove the printf_begin() statement from setup() and the two functions serial_putc and printf_begin. I did this and was happy that there’s not something weird going on and it worked identically. This page has been particularly helpful to me as I’m in the process of selecting sensors for my model train table. In my environment the… Read more »

Ryan
4 years ago

Hi,
very nice test.

I have a question, i bought 4 Sensors TOF10120.
The problem is, all Sensors have the same I2C adress (0x52)

Do you know how i can change the address?

3 years ago
Reply to  Ryan

Data sheet says to send routine, but not to sure myself

Command = string input box Send = s4-1000 # Explanation = OK Return information = set successfully: ok means the distance is set up to 1000mm

Set I2C slave ID
Command s7-xxx #
Return information > Setting success: ok Setting failed: fail
Description
xxx = 1 ~ 254 (0x01 ~ 0xFE) Default 164 (0xA4)

3 years ago
Reply to  Ryan

You may be able to write the i2c address using the UART mode — I ran the datasheet through google translate — see https://github.com/simpleiot/reference/blob/master/sensors/TOF10120_english.pdf for details.

3 years ago
Reply to  Cliff

I did end up changing the address, I posted the method here, as you said I used UART instead of i2c

https://forum.arduino.cc/index.php?topic=663712.0

jean-pierre legrand
4 years ago

Hello, Interesting video. I am really amazed by the lack of reliability in the measurement by the TOF10120 sensor. I notice that the measurement by the HC-SR04 sensor is displayed with two numbers after the decimal point, that is to say in tenths of a mm. It is surprisingly very precise in the 25 cm / 50 cm area. Have a good day jPL Bonjour, Vidéo intéressante. Je suis vraiment étonné par le manque de fiabilité dans la mesure par le capteur TOF10120. Je remarque que la mesure par le capteur HC-SR04 s’affiche avec deux chiffres après la virgule, soit… Read more »

Brett A. Langley
3 years ago

After watching the video and seeing the problem with the ultrasonic reading past 50cm, I wondered what would happen if you used a piece of tubing as a waveguide to narrow the field. It should not affect the speed and it might narrow the beam enough to get past the obstruction in the field of view.

Alex Santos
11 months ago

I’ve already tested it on a 100mm water pipe and it went up to 6m.

Uttam Dutta
3 years ago

Regarding TOF10120– how it is projected, in a straight line or diverging , if diverging ..then accuracy effected with the increased distance ?

MikeH
3 years ago

I’m not too sure I agree with all your conclusions; you employed filtering for the ultrasonic and excused it that it couldn’t read >50cm. Yes the laser gave poor results >50cm but it gave results. Nonetheless, thanks for your videos. As others I tracked down a data sheet and let a translator do its job. I created a short sketch for a Nano to employ an AltSoftSerial for the TOF10120. There are comments in the ocde. /*  Exploring the TOF10120 laser distance module.  Program run on Nano  TOF10120 connected to both I2C (A4/A%) and  AltSoftSerial so that the Serial remains… Read more »

Tony
3 years ago

Hi. Great article and video. I am trying to compile the code from this article, using Arduino 1.8.12 IDE, with the TOF10120 wired up to an Arduino Mega2560. I get this error during compile.

In file included from C:\Users\airbo\Downloads\TOF10120_i2c_SerialM\TOF10120_i2c_SerialM.ino:6:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src/Wire.h: In function ‘void SensorRead(unsigned char, unsigned char*, unsigned char)’:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src/Wire.h:64:13: note: candidate 1: uint8_t TwoWire::requestFrom(int, int)

uint8_t requestFrom(int, int);

^~~~~~~~~~~

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src/Wire.h:61:13: note: candidate 2: uint8_t TwoWire::requestFrom(uint8_t, uint8_t)

uint8_t requestFrom(uint8_t, uint8_t);

I can see the laser is on, via my phone’s camera.

Any ideas?

magicChristian
3 years ago

I worked with Ultrasonic Rangefinders some while and want to give some remarks: They always are calculating the first reflex which is strong enouph. You must take care if you want the distance of an small thing like a rod and the angle of the part is important. If the target is tall enouph the accuracy when calculating temperature and humidity is great. The field of view is quite large – there are none “pencil beam” sensors available. I tried to enhance one US Sensor with an extra µC to give the distances of all reflecting targets within a range… Read more »

2 years ago

You are one of the best online teachers that I have come across. Hope you will teach young people about robotics in a simple way like you do now. Take Care and keep up your wonderful work. Thanks, Gehard. 

keyur
2 years ago

What is the field_of_view of TOF10120.. I found HCSR04 quite inaccurate at times due to its 30degree fov.. have noticed tht such VCSEL sensors have lower fovs.. how much is it for TOF10120 ?

Maarten
2 years ago

Hallo, 

I am testing my TOF10120 with my Adruino Uno.
I copied the code en get a following erro code:

“‘fdevopen’ was not declared in this scope”

How to solve this?

Many thanks,

Maarten.

Dr Bwts
1 year ago

Thankyou for the article, just a point about the TOF10120 code. My Arduino compiler complained in the SensorRead function in step 3 Wire.requestFrom(82, cnt);I had to explicitly declare a variable at the begining of the function for the device address, uint8_t dev_add = 82; and use that instead, Wire.requestFrom(dev_add, cnt);

Aashish M N
16 days ago

Can i use the TOF101 to detect black or a white line, because the reflective sensors like IR are very bad with a distance of about 10cm, if yes then my other doubt is whether i can use it by mounting it in a 45degree angle facing the ground and still able to get the readings accurately ?