Introduction: Simple Ultrasonic Distance Sensor Module Demo

As with some of my other Instructables my goal here is to give you, what I found to be, the simplest way to get this sensor up and running before you get discouraged and throw it out. PS: If you do get to that point, my mailing address is PO Box ....

The HC-SR04 Ultrasonic Distance Sensor (and like modules) uses ultrasonic sound waves to determine the distance to an object. Hmm, well actually we have to figure out the distance because the sensor itself simply holds it's "ECHO" pin HIGH for a duration of time corresponding to the time it took to receive the reflection (echo) from a wave it sent. Say WHAT?

1. The module sends out a burst of sound waves, at the same time it applies voltage to the echo pin.

2. The module receives the reflection back from the sound waves and removes voltage from the echo pin.

That's all folks! That's all the module does. We can determine the distance because we know how long it took for the sound waves to travel out from and back to the module (by how long the echo pin was HIGH) and we know the speed of sound in the air. But I ain't getting into that. We're going to let Arduino figure out that stuff.

UPDATE 11/20/15: after publishing this Instructable I did find out that although Ultrasonic Distance Sensors all function basically the same way, they DO NOT all provide the same output on the ECHO pin. If you are not using a HC-S04 module, check Step 4 Known Issues to see if your module is listed. If it's not listed I'd be interested in knowing if it works or not for you.

UPDATE 01/20/16: added code for the DYP-ME007TX module.

So let's get setup for this...

(Oh yeah, you want very inexpensive prices on modules, check it out

http://www.icstation.com/index.php?cPath=79&aid=5...

Step 1: Setup

Pretty simple setup here. (remember to remove any power source connected to your Arduino and/or breadboard before you start)

1. Connect the 5v out from Arduino to Vcc on the module

2. Connect the GND from Arduino to the GND on the module

3. Connect Arduino's digital pin #7 to the Trig pin on the module

4. Connect Arduino's digital pin #8 to the Echo pin on the module

And finally, some simple code...

Step 2: HC-SR04 Coding

You will need to have Arduino's serial monitor running to see the output from the sketch below. If you are unfamiliar with the serial monitor now is your chance to use it! It's a great tool for debugging and whatnot. In the Arduino interface look up at the right hand corner, the button to start the serial monitor is there. It looks like a magnifying glass to me, just click it and the monitor will open (or select TOOLS/Serial Monitor, or Ctrl+Shift+M).

Well this would have been a simple little sketch if I didn't comment the he** out of it! :-)

// Arduino Sketch Begin -

// Defining Constants (constants are things that will not change, you'll get a compile error if you try to change the value of a constant within the sketch)

const int triggerPin = 7; // creates a constant named "triggerPin" and assigns digital pin 7 to it

const int echoPin = 8; // creates a constant named "echoPin" and assigns digital pin 8 to it

// Defining Variables (variables can and normally will change within a sketch, they are basically storage locations for values)

int duration = 0; // creates a variable named "duration" to store the value returned by pulseIn, the value is being preset to "0"

int distance = 0; // creates a variable to store the value calculated to be the distance to an object in front of the sensor, the value is being preset to "0"

void setup() // Use this section to configure your board and other features as required by your program

{

Serial.begin(9600); // initialize serial communications via USB between Arduino and computer, you are going to need it

//defining pin modes

pinMode(triggerPin, OUTPUT); // "triggerPin" will be used for OUTPUT, the pin number is declared above under Defining Variables

pinMode(echoPin, INPUT); // "echoPin" will be used for INPUT, the pin pin number is declared above under Defining Variables

} // end of setup

// everything above this point is only read once by a program - at Startup or Reset

void loop() // the sketch in the loop section is read continually and repeated until power off or reset

{

digitalWrite(triggerPin, HIGH); //starts the Ultrasonic wave(s) out from the HC-SR04 module

delay(5); // short pause for the cause - required for module to function correctly (you can lower the number, I run it at 1 in other sketches)

digitalWrite(triggerPin, LOW); //stops the Ultrasonic wave(s) out from the HC-SR04 module

duration = pulseIn(echoPin, HIGH); //special function to determine the length of time the echo pin was held HIGH by the last completed cycle of sound bursts

delay(10); // short pause for the cause. This delay is for stability, too short a delay and no worky

distance = (duration/2) / 74; //transforming duration to distance (the value stored in "duration" is divided by 2, that result is then divided by 74**) ** for centimeters (cm) divide by 58, thanks coytar!

delay(500); // delay for stability - can play with it but can also break things doing so - use 500 for default

Serial.print(distance); //sends the value calculated to be the distance to the serial monitor

Serial.println(" inches"); //adds the word "inches" after the distance value above and starts a new line on the serial monitor

Serial.println(); //adds a blank line on serial monitor for readability

} // End of Loop

_________________________________________________

Ok, after reading my own Instructable I realized that the sketch above doesn't really meet my definition of "simple". So here's the exact same sketch, commented lightly.

// HC-SC04 Ultrasonic Distance Module Sketch by Brad

const int triggerPin = 7; //trigger on 7

const int echoPin = 8; // ECHO on 8

int duration = 0; // hold value from pulseIn

int distance = 0; // hold value for calculated distance

void setup()

{

Serial.begin(9600);

pinMode(triggerPin, OUTPUT); //defining pin modes

pinMode(echoPin, INPUT);

}

void loop()

{

digitalWrite(triggerPin, HIGH); // start sending sound wave(s)

delay(5); //required, can be adjusted (no lower than 10us)

digitalWrite(triggerPin, LOW); // module stops sending wave(s)

duration = pulseIn(echoPin, HIGH); // determine how long the ECHO pin was high for the last complete wave

delay(10); //required, can be adjusted - carefully

distance = (duration/2) / 74; delay(500); // calculating distance ** for centimeters (cm) divide by 58 ** thanks coytar!

delay(500); // delay for stability - can play with it but can also break things doing so - use 500 for default

Serial.print(distance); // send the current value stored in distance to the serial monitor

Serial.println(" inches"); // displays the word "inches" after the distance above

Serial.println(); // creates a blank line on serial monitor for readability

}

There, now that's a simple sketch!

The included .ino files are;

1. HCSR04BareBones.ino - this file is heavily commented and includes some basic specs for the HC-SR04 module as well as wiring instructions.

2. BareBonesLight.ino - very lightly commented

Step 3: Tips and Tricks

Here's a tip, I know this code works, yet when I downloaded and ran the file I attached to this Instructable (just double checking before I publish) it didn't work! What the ...., I spent about 45 minutes on this simple little thing trying to figure out why all I got on the serial monitor was "0 inches". I finally replaced the HC-SR04 module I was using with another one, guess what - that fixed it.

Watch the programs response if you play with any of the delay times. I found out the hard way that to short a delay, or none at all, in certain parts of the script will stop everything from working.

Once you have everything working your imagination is your only limit - you could use this to monitor a stationary object to make sure it stays stationary. Or you can use it to alert you when an object moves past the sensor. Or you can use it to .... (your turn).

The breadboard above is from another project I have completed where everything is cool until something gets closer than 24" to the sensor. But it doesn't just scream at me the second that happens. That project uses three LEDs and a buzzer. When there's nothing closer than 24" the Green LED is on. When something moves closer than 24" in front of the module the Green LED goes off and the first Red LED comes on. Now, if the object stays closer than 24" for a set period of time the other (brighter) Red LED and buzzer are activated. When the object moves back more than 24", the alarm - if it's on - and the Red LED(s) turn off and the Green LED is turned back on. I said, if the alarm is on, because something can move within 24", turning on the 1st Red LED, but not trigger the second Red LED and alarm by moving further back before the time to do so expires. That won't stop all false alarms but it should eliminate those caused by birds flying by or squirrels scampering through the sensors path, stuff like that.

Step 4: Known Issues

If you see the model number of your Ultrasonic Distance module below, locate the troubleshooting section for it. Hopefully you'll find what the issue is and a solution.

1. US-105 (shouldn't be hard to find the troubleshooting section at this point)

2. DYP-ME007TX

US-105 module

The US-105 Ultrasonic Distance Module uses GPIO output on the ECHO pin, this requires different calculations to determine distance. With GPIO output the ECHO pin is NOT held HIGH when a wave is sent. Instead, when a reflection from a wave is received a particular voltage is applied to the ECHO pin. That voltage being proportional to the time it took to send and receive the wave.

The following sketch has been reported to work with that module (thanks to member luigisf for this info)

// Code for Ultrasonic Distance Module US-015

unsigned int EchoPin = 2;

unsigned int TrigPin = 3;

unsigned long Time_Echo_us = 0;

//Len_mm_X100 = length*100

unsigned long Len_mm_X100 = 0;

unsigned long Len_Integer = 0; //

unsigned int Len_Fraction = 0;

void setup()

{

Serial.begin(9600);

pinMode(EchoPin, INPUT);

pinMode(TrigPin, OUTPUT);

}

void loop()

{

digitalWrite(TrigPin, HIGH);

delayMicroseconds(50);

digitalWrite(TrigPin, LOW);

Time_Echo_us = pulseIn(EchoPin, HIGH);

if((Time_Echo_us < 60000) && (Time_Echo_us > 1))

{

Len_mm_X100 = (Time_Echo_us*34)/2;

Len_Integer = Len_mm_X100/100;

Len_Fraction = Len_mm_X100%100;

Serial.print("Present Length is: ");

Serial.print(Len_Integer, DEC);

Serial.print(".");

if(Len_Fraction < 10)

Serial.print("0");

Serial.print(Len_Fraction, DEC);

Serial.println("mm");

delay(1000);

} // End of Sketch

End US-105 Troubleshooting ____________________

DYP-ME007TX

The following code has been tested and does work with the DYP-ME007TX module

// DYP-ME007TX Arduino Sketch

/* WIRING INSTRUCTIONS
* 5V from Arduino to VCC on module
* GNG from Arduino to GND on module
* OUT from module to Digital Pin 7 on Arduino
*/

#include
#define RXpin 7
#define TXpin 7
SoftwareSerial mySerial(RXpin, TXpin);
long mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;
void setup()
{
Serial.begin(9600);
mySerial.begin(9600);
}
void loop()
{
bitpos = 0;
while (mySerial.available())
{
if (bitpos < 4) {
mybuffer[bitpos++] = mySerial.read();
}
else break;
}
mySerial.flush();
mili = mybuffer[1] << 8 | mybuffer[2];
Serial.print("Distance: ");
Serial.print(mili / 25.4);
Serial.print (" inches");
Serial.println();
delay(500);
}

Comments

author
chrisjlionel made it!(author)2016-08-15

Cool.

WhatsApp Image 2016-08-16 at 7.19.05 AM.jpeg
author
edoardoelite made it!(author)2016-03-10

Hi Guys,

I would like to realize a sensor which keep every single passage of "something" in front of it, and let me know the frequence of passing.

I don't need to know the distance, but monitoring the distance changing to know how many times per minute the object pass in front of the sensor.

I tried to check to do something with this sensor, but if I pass the object not always on the same position, and very fast ( from 60 to 130 times a minute ) I risk it doesn't read the passage.

Do you have any help?

Thanks

author
Heyup made it!(author)2016-02-01

Great tutorial, Thank you very much... John :) ...

author
gr8yt made it!(author)2016-01-20

added code for the DYP-ME007TX distance sensors under the troubleshooting step.

author
gr8yt made it!(author)2016-01-20

Hi, what type of display and what do you want to display (I'm assuming the distance but you never know 'eh)

author
pradyumna+s+nadig made it!(author)2016-01-20

what if i want to add a display

author
gr8yt made it!(author)2015-12-19

happy holidays

author
narcotikas made it!(author)2015-11-29

THANKS , I TRY TO MAKE THIS !!

author
gr8yt made it!(author)2015-11-29

Great! Don't be shy, let me know if you have any trouble. I'm always willing to help if I can.

author
judas79 made it!(author)2015-12-08

I was about to totally give up on my 3 pin DYP-ME007TX Ultrasonic Module, until I saw your offer tol HELP with modules that need alternative code. I have asked the reseller, on eBay, searched high and low for example code without much success; I did find a post in Italian from long ago using an outdated (new serial library) which no no longer works with the Arduino's modern IDE's. They still sell these modules on eBay.

s-l300.jpg
author
gr8yt made it!(author)2015-12-08

So that little baby is using serial output, but I guess you knew that with the mention of the serial library in your note. Anyway, you are definitely not the first person to have trouble getting usable data out of that particular sensor. I did manage to locate some code that I believe may work for you. I will send that to you. For this code, connect OUT from the module to pin 6 on your Arduino.

author
gr8yt made it!(author)2015-12-08

Let me take a peak at that and see what I can find. Don't give up yet!

author
Nextprojectawesome made it!(author)2015-12-02

Yup, this instructable gave me the perfect start! Cheers!

author
Nextprojectawesome made it!(author)2015-12-01

The code I wrote is actually "serial" send/receive logic that my Pi initiates the check to ask the Arduino if the glass is present, if it is there it initiates pouring.

Im curious about the high level of what you are thinking of, but wouldn't want you to put effort in actually coding it.

author
gr8yt made it!(author)2015-12-02

I love it, looks like you have things well in hand.

author
gr8yt made it!(author)2015-12-01

That's great! If you are interested, at the end of this Instructable I mention another project where I use the measured distance to trigger some alerts. The code for that project code easily be modified to tell you when there is a glass on the tray. It can also tell you when that glass arrives on the tray and it can tell you when the glass leaves the tray. If that does interest you let me know and I can make some quick adjustments in the code and send you that.

author
Nextprojectawesome made it!(author)2015-11-30

Pic of it working

photo-2015-11-30, 11:43 PM.jpg
author
Nextprojectawesome made it!(author)2015-11-30

Btw, turns out because the space is so confined one sensor was sufficient to tell if a glass is there.

author
gr8yt made it!(author)2015-11-28

Update: corrected breadboard pic under Tips and Tricks, had one positive line trace colored black instead of red. Nope, that was NOT the error I mentioned earlier. That error is in the code. Again though, it is a minor error and does not have any affect on how the sketch runs.

author
gr8yt made it!(author)2015-11-26

Can't find my mistake? OK, I'll give you a clue. It's in the first script, the heavily commented one, and it's near the top - wait that's two clues.

author
gr8yt made it!(author)2015-11-24

oh boy, oh boy, oh boy - I can't believe it, I just found a mistake in my script (nothing critical) I can not begin to tell you how many times I have read that script and missed this. But I ain't gonaa feels two bd bout it cuz apairantlee yu alll did two

I ain't fixing it till someone finds it!!

author
Nextprojectawesome made it!(author)2015-11-23

Ok I tried your program and it would totally work. See image. Pretend bb8 was a glass. Sensor 1 says 4" away, and sensor two says 4" away. Knowing center is 7" away from each sensor, i can calculate the glass diameter for , or rather radius of 3"

photo-2015-11-24, 12:26 AM.jpg
author
gr8yt made it!(author)2015-11-23

I love it!

author
Nextprojectawesome made it!(author)2015-11-23

Or more accurately

photo-2015-11-24, 12:40 AM.jpg
author
Nextprojectawesome made it!(author)2015-11-23

Thanks for doing this!!!! I want to use this to tell if there is a glass on a drink tray. If I use two sensors, do you think I could calculate the size of the glass on my project???

author
gr8yt made it!(author)2015-11-23

You are welcome, I appreciate the kind words. Off the top of my head I don't see anyway to calculate the size of the glass using these modules. You could use the weight of the tray to determine if something has been placed on it. The glass size could also be determined by weight, but that throws a lot a variables into the mix. Is the glass full or empty, a small glass could weigh the same as a large one if the small one is full and the large one is empty.
I will keep your question in mind while I'm playing. The size of an object is something I'll want to be able to determine as well for a project I have in mind.

author
gr8yt made it!(author)2015-11-20

Somebody stop me!!! I can't leave this thing alone!! I added another .ino file called BareBonesLight.ino - this file does not have all of the heavy commenting included in the original BareBones.ino file.

author
coytar made it!(author)2015-11-20

Stop! :)

author
gr8yt made it!(author)2015-11-21

Can't - ADHD/ODC , try looking that function up! :-))

author
gr8yt made it!(author)2015-11-21

Ok, so it seems we just can't leave well-enough alone for long around here 'eh. JUST KIDDING!! That's actually a good thing, "well-enough" can get you in trouble with electricity really fast!

I have edited the Instructable to include the centimeter divisible of 58 provided by coytar. I also edited both embedded files to include that information as well.

Can I go to bed now?

author
coytar made it!(author)2015-11-20

Nice work, thanks! In case anyone was wondering, divide duration by 58 to get the distance in centimeters.

IMG_20151121_160922.jpg
author
gr8yt made it!(author)2015-11-21

thank you!! I kept forgotting about that or found something else to do when I should have been looking it up. Know I don't have to. :-)

I will add that info, appreciate the note.

Thanks

author
gr8yt made it!(author)2015-11-20

added Step4 Known Issues to Instructable, thanks again to member luigisf for bringing this to my attention.

author
gr8yt made it!(author)2015-11-20

From what I'm reading the format of GPIO output is in the form of TTL logic. Hope I said that correctly. Anyway, what I believe to be the issue is that the HC-SR04 holds the ECHO pin HIGH from the time it sends a wave out until it receives the reflection from the wave and then brings the pin LOW. The GPIO output is different in that when that module sends a wave out, it does not bring the ECHO pin HIGH. Instead it waits for the reflection and then applies (X)voltage to the ECHO pin. That (X)voltage is the time between wave out and reflection. So the "distance" is determined by how long the ECHO pin is HIGH for the HC-SR04 wherein it is determined by the voltage applied to the ECHO pin for the US-015.

To me, that explains why the US-015 still uses the same pulseIn function but completely different mathematics to calculate the distance.

And don't be shy people, please tell me if I am wrong. I'd rather know about, and correct my mistakes, rather then leaving them out here to mess someone else up.

author
luigisf made it!(author)2015-11-19

You know, I was having a grand ole time getting frustrated at my module for not working with your code, until I finally thought to actually look at it and realize that I have the US-015 module instead of the hc module with the crystal in the front. No wonder it was giving me so many zero inch measurements! In case anyone does need a code for that one, I found it at http://www.wayengineer.com/us015-instead-of-hcsr04...

Thanks for the great instructable, it sure helped me get acquainted with my arduino!

author
gr8yt made it!(author)2015-11-20

Hi luigisf, thank you for that info. I looked at the US-015 because my first suspiscion was a different pin configuration - nope, they are the same. As I don't have a US-015 module would you mind playing with some code changes to the sketch included with this instructable for me? I promise I won't take up too much of your time (I'm lying, I will use you like a dog until I figure out the difference in the modules).

I looked at the code in the link you provided. Guess I know what I'll be doing today - learning more! But then that's why I like doing this stuff, learning.

HEY EVERYONE ** One thing I noticed about the US-015 is that it states the output from the ECHO pin is in GPIO format, I never saw the output on the HC-SR04 referrered to as being GPIO. Can anyone tell me that "GPIO" is / or is not the problem? I've done some quick research on that question myself, but I haven't come up with the answer yet.

author
teknohawk made it!(author)2015-11-17

Thank you for this informative instructable! I have been working on a simple robot, and needed exactly this; a simple, bare bones tutorial to lay out the basics. Thanks!

author
teknohawk made it!(author)2015-11-18

Ha-ha that's the best philosophy out there

author
gr8yt made it!(author)2015-11-18

Thank you, you are the reason I write these up! Well not just you, but anyone that just wants to see it working and then build from there. I work by an ancient eastern philosophy; K.I.S.S. (Keep It Simple Stupid)

author
N1GG9 made it!(author)2015-11-17

HOLY SHIG THISWAS COOL THANKSXXXXXXX :DD

Untitled.png
author
gr8yt made it!(author)2015-11-18

You're welcome. And thank you, I appreciate the shig out of your comment.

author
gr8yt made it!(author)2015-11-18

UPDATE: I edited Step 2: I read my own Instructable and realized I said I'd give you a simple sketch. My heavily commented sketch isn't what I'd call simple, so below the heavily commented sketch you will now find the exact same script with only a few comments. The included .ino file is the heavily commented version, in fact it has more comments as I included information on the module also.

About This Instructable

10,333views

219favorites

License:

Bio: Hi, I'm Brad. My interests spread over a large area and I tend to get carried away when something new peaks my interest. I ... More »
More by gr8yt:D2-3 Tracking & Obstacle Avoidance Smart Car DIY KitLED Cycle Light ReviewSimple Serial Converter Makes Pro-Mini Programming Easy
Add instructable to: