Simple Ultrasonic Distance Sensor Module Demo
by gr8yt in Circuits > Arduino
16056 Views, 216 Favorites, 0 Comments
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...
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...
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 -
/* below we start by defining constant variables - constant variables do not change, you'll get a
compile error if you try to change the value of a constant variable within a 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
/* now we define our 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", its current value is set to "0". This variable
// will store the data from pulseIn
int distance = 0; // creates a variable named "distance", its current value is set to "0". This variable
//will store the value calculated to be the distance to an object in front of the sensor
void setup() // Use this section to configure your board and other features as required by your program
{ // beginning of setup
Serial.begin(9600); // initialize serial communications via USB between Arduino and computer
//next 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 code in the loop section is repeated until power off or reset
{ // beginning of Program Loop
digitalWrite(triggerPin, HIGH); //STARTS the Ultrasonic wave(s) out from the HC-SR04 module
delay(5); // short delay - required for module to function correctly
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 complete cycle of sound bursts
delay(10); // short delay - for stability, too short a delay and no worky
distance = (duration/2) / 74; //calculate distance (inches) based on duration
delay(500); // another delay for stability
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 Program Loop (begin again at Beginning of Program 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!
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 too 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.
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);
}