Simple Ultrasonic Distance Sensor Module Demo

11,805

218

37

Published

Introduction: Simple Ultrasonic Distance Sensor Module Demo

About: 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 picked up my basic electronics knowledge in bed. Say what? I was laid up after surg...

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);
}

3 People Made This Project!

Recommendations

  • Oil Contest

    Oil Contest
  • Water Contest

    Water Contest
  • Creative Misuse Contest

    Creative Misuse Contest

37 Discussions

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

0
user
Heyup

2 years ago

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

0
user
gr8yt

2 years ago

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

0
user
gr8yt

2 years ago

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

0
user
gr8yt

2 years ago

happy holidays

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

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

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.

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

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

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.

1 reply
0
user
gr8yt

2 years ago

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.

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

0
user
gr8yt

2 years ago

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.

0
user
gr8yt

2 years ago

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.

0
user
gr8yt

2 years ago

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!!