LESSON 18: Distance Meter Using Ultrasonic Sensor and Arduino

In Lesson 17 we learned to use an ultrasonic sensor to measure the speed of sound. There is a different way to use the sensor. Since we know the speed of sound, we can use it to measure distance, since d = r*t (distance = rate * time). You know the rate, that is the speed of sound. You can measure the ‘time’ using the ultrasonic sensor, just as you did in Lesson 17. This is the time for a ping to go from the sensor to the target and back. Knowing this, you can then calculate the distance to the target.

Arduino Distance Sensor
Arduino Distance Sensor Displays Measured Distance with a Servo

For you hackers, just jump right in and do the assignment. You should be able to do it with what you have already learned. What I want you to do, though, is come up with some creative way to display the distance . . . something better than just printing it on the Serial Monitor. I will make a scale and display it using a servo. You can do whatever you think would be most interesting. For those who need a little extra help, I will step you though my project below.  The first thing you need is to hook up your circuit. I have the sensor hooked up like in Lesson 17 and have added a servo. The servo black wire needs to hook to ground, the red wire to 5V from the arduino, and the white wire, which is the control wire, I have hooked to pin  6 of the arduino. Remember that you need to verify that your servo will not draw too much current from the Arduino. The servos in the Sparkfun Inventor Kits work fine, and can be driven directly from the arduino 5V power pin.  Also, your servo might have different colored wires. Many have Red for power, Orange for control , and Brown for Ground.  Always confirm the color code with the data sheet for the specific servo you are using. Also, remember that before using a servo, you need to determine its suitable range of motion. This was explained in Lesson 16.  For my project, I am using the following schematic. It would be better to hook to the ultrasonic sensor by putting the wires behind the sensor, so they do not interfere with the ‘ping’ coming from the front. I drew them in front so you could see them clearly, but wire them on the back side of the sensor.

Ardunio-distance-sensor
Arduino Circuit for Measuring Distance.

When you get your circuit set up, we will need to do some math. Our objective is to measure distances between 0 and 7 inches. This sensor could probably do a good job measuring distances up to three feet, but for this project we will focus on 0 to 7 inches. We then want to put a pointer on the servo, and have it point at a scale that will indicate distance. Since the servo swings in an arc, we can best thing about the output of the servo as an angle. On the scale I draw, I want to have the numbers be between angles of 37 degrees and 143 degrees. For a distance measured of 0 inches, I want the servo to point at 37 degrees. For a distance measured of 7 inches, I want to point to 143 degrees. Then, everything should scale between those numbers.  You can see that I drew my scale for my servo above on a piece of polar graph paper. Polar graph paper makes it easy to draw specific angles and ranges of angle. You can print your own polar graph paper at HERE.  Now, the math that has to be done is to calculate the angle you should set your servo at based on what distance measurement you are reading. The numbers have to match the scale you draw for the servo. For mine, I want a measurement of 0 inches to put the servo at 37 degrees, and a measurement of 7 inches to put the servo at 143 degrees. These match the positions of the ‘0’ and ‘7’ on my scale. By this time you should be comfortable doing the math, but if you need help, you can check my notes below.

Servo Math
These notes show you how to calculate servo position based on measured distance.

You will need to draw our own servo scale. You can arrange the scale however you like, but in the end, you have to do the math so that your servo points at the right distance number on your scale.

With that out of the way, we now need to do the coding. There is not really anything new to learn as far as coding goes. This is really a combination of what you learned in lesson 16 and lesson 17.  In this project though, instead of measuring the speed of sound, we will be measuring the distance to a target, given the known speed of sound. Then we use the math above to calculate where to point the servo. The video above will take you through the code step by step, but I include the code below. You should not copy and paste the code, but just look at it if you get stuck. For those of you in my class when I check you project for a grade, I will be looking to see if you are working independently, or just copying what I am doing.

Now your assignment is to come up with a new and different way to display the distance. On this new assignment measure distances between 0 and 18 inches. Figure out a cool way to convey that distance to the user. Think of a good idea. If you are having trouble coming up with an idea, maybe build a bar graph with 10 LED’s, and the number of lit LED’s indicating distance. In any event, you will need to do your math on the project, and an important part of the grade is showing me your graph where you map your output values onto your input values, like I did above.

24 thoughts on “LESSON 18: Distance Meter Using Ultrasonic Sensor and Arduino”

  1. thank you so much for the generosity of sharing you wonderful experience and great knowledge. i just want to ask, is there any way that i can interface the ultrasonic sensor with Matlab using code or simulink block?
    could you please help me out of this.
    thank you so much

    1. I focused on python and Matplotlib because those are free packages. I have not done tutorials with Matlab, as that is an expensive package, and most of what you need you can do with the free package.

  2. What amount of voltage does your servo need? Mine doesn’t work because the the arduino does output enough to power both the sensor and the servo.

    1. it is probably not voltage but current drive. Many larger servos can not be driven by the arduino. You can still control it from the arduino but connect power to external power supply of proper voltage.

  3. Thank you for this great insight you have given me. I am doing a project like this but wanted to know if there was a way to edit this code to record the different distances of the object when it is moving at different points in time in order to calculate the speed of the object . Thank you.

    1. That is probably doable . . . I would make an array, and then calculate speed from adjacent points. Will probably have to do some averaging, and managing the array so you do not keep too many points.

  4. At 75years young, I just bought my Arduino Uno and a box of bits to go with it. Then I found your website !
    What a brilliant tool to learn with. I want to tell you it is great having you talk me through the tutorials in a language I find easy to understand.
    I have completed lessons 16/17/18., they all work really good, and I feel confident to tackle lesson 19.
    Great work, please keep it going.
    Many thanks
    Victor

  5. For school we need to make an arduino self driving car. We have an arduino with a proximity sensor and a servo and we need a program wich let the servo steer left or right if we approach an object. Do You have any ideas, we are no experts in arduino? Thanks!

    1. My suggestion is to start with simpler projects and build up your skills. You need to learn Arduino before robotics. My suggestion is to go through the lessons on this site, and then start learning robotics after you are really good in the arduino

    1. YOu are correct, and that is the normal and easy way to do it. My goal in this lesson is to teach my High School students how to recognize how to use the math they have learned in math class to solve real problem in real world. Students are good at learning math, but poor at recognizing how to use it.

      1. On the contrary! After reading this lesson and trying it out in ‘practice’ I find that the “map” function seems a lot more complicated, at least for me. The “math-way” seems a lot more logical. Although in elementary school where I teach, kids are having a lot of difficulty in applying the knowledge they got in their math classes – I’m talking about 8th graders…. they seem to grasp the ‘map-thing’ somehow easier…. don’t know why though….

        For me, math is definetly the way to go.

      2. Just a thought…
        In my further research I have found the “constrain” funtion very useful from the servo-side point of view….
        I get a lot of gitters from the servo when the sensor gets out the given limits 0-7in. (the Serial Monitor is showing values that are not consistent with the ‘real world’)

  6. First of all thank you very much tfor shairing your knowledge with us.I am an engineering final year student i am doing a project of pothole detection by sonar sensor on the road while a vehicle driven. so i need your guidense to success my project perfectly. So wich is the most suitable and low cost ultrasonic sensor

  7. Hi,
    Its a great experience to me as a new comer to Arduino projects. I’m taking this concept into another project for automatic curtain opener using stepper motor instead of servo in this project as to carry the weight of curtains. So my question is that possible to load the stepper motor library instead od servo library as well in pinmode for motor in the sketch. I shall be thankful if you could explain to me the possibilities. Thank you.

  8. Thanks for sharing It’s very helpful and i want tell you good work and go we with you i ask you how we masure highte jump in vertical and thanks

  9. Respected Sir,

    In my physics class, I have studied that a pulse undergoes inversion after hitting a fixed end. Thus, at pulseIn() shouldn’t we technically be reading a LOW pulse rather than a HIGH pulse.
    Thank you

  10. hello sir,
    your videos on youtube are really of great use. thank you so much.
    can those ultrasonic sensors detect water??

  11. Thankyou so much for the code. I just had a little problem while doing my own project. I want to rotate the servo motor in anticlockwise direction and then calculate the distance as well as angle. How to do that..? Here, in the above written code, we are not rotating it in any particular direction..the motor is itself rotating in a clock wise direction..It would be wonderful if i get some suggestions regarding this. I am just a novice..Thankyou..!

  12. Hello sir ,
    I know that it’s too late for me to comment on your video as its about 3 years past …. But still I request you sir to upload video on “Infrared Sensor”. And mainly on “Line following robot”.
    And also please help me out in how to reverse a DC motor once a signal comes from a ultrasonic sensor if the distance approached by sensor is too close…..
    I know it’s too late but still having hope that you would help me out sir..
    Thank you for your support till this point and hoping your reply for this request…..Thank you

Leave a Reply

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