loading
Picture of Simple Arduino and HC-SR04 Example
HC-SR04_LED_fz.jpg
top.JPG
After buying a HC-SR04 from Amazon, I could not get it to work out of the box. Not wanting to concede I had a DOA sensor on my hands, I searched for a simple example setup. After spending far too long on this than I felt I needed to, I decided to make this instructable to help other emerging tinkerers get their project off the ground.

I admit this example is more than bare-bones in that it has LEDs, but this lets me test it without needing a PC to show distance and check the accuracy of the sensor.

Step 1: Parts List

Arduino UNO R3 (I use the Adafruit mount)
One (1) HC-SR04 Ultrasonic Sensor
One (1) Red LED
One (1) Green LED
Two (2) 560 ohm (Green, Blue, Brown, Gold) Resistors
Half Breadboard
Eight (8) Male/Male hookup wires
A ruler that measures centimeters (or use the serial monitor)

Step 2: Connect the components

Picture of Connect the components
HC-SR04_LED_fz.jpg
Connect the components and wires as shown in the two pictures.

Step 3: Upload the sketch

Copy the sketch to your Arduino and watch the blinky lights.
 


 
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
More info at: http://goo.gl/kJ8Gl
Original code improvements to the Ping sketch sourced from Trollmaker.com
Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
*/

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 4) {  // This is where the LED On/Off happens
    digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
  digitalWrite(led2,LOW);
}
  else {
    digitalWrite(led,LOW);
    digitalWrite(led2,HIGH);
  }
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}
 
1-40 of 158Next »
Can the Arduino be made to act like a k2 metre.
I have a challenge for you to try. Could the Arduino Be made to act like a k2 metre.

This was very helpful in making my prototype parking sensor, thank you!

2015-08-19 21.08.23.jpg
agu3rra made it!14 days ago

Great tutorial. Thanks!

DSCF4897.jpg
luisb1423 days ago

hola, como puedo añadir una matrix de dos colores en vez de dos led, la matrix dira en color verde siga y la roja Pare.

luisb1425 days ago

Hi

Im trying to replicate the ''Arduino Tone 3'' tutorial, except replacing the 3 force sensors with 3 HC-SR04's.

can this be done?

would be great to hear some ideas

flseadog1 month ago

Thank you. I was pulling my hair out trying to get this to work with the Ping code from arduino robot bananza book. I needed the echo wiring and code. Now it works great.

jueljp1 month ago

thanks

Thanks, worked first time!

Hy.

my name is abdu

thnx 4 ur every replies

How can I add a motor which will start rotating if the distance b/w the sensor and any object is more than 1 meter and stop rotating when the distance between them becomes less than 1 meter..?

would you please give me detailed circuit diagram and its code.

The HC-SR04 gets activated with an input signal, then you check the amount of time before the output pin goes hi. This time, in microseconds, divided by 148 give the number of inches the sensor is from the object.

Here is video showing an example of sensing distance. Code is given by the fellow who made the video (not me.)

here is some non-function code:

loop(){

static int far_away=0;

static int motor_on=0;

far_away=verify_distance(); //this function returns 0 when too close, else 1.

motor_on=0; //play it safe, with the default being the motor is off.

if( far_away ){

motor_on=1;

}

my_pin=activate_motor(motor_on);

set_output_pin(my_pin); //view motor state

sleep(1 second);

}


How can I add a motor which will start rotating if the distance b/w the sensor and any object is 'x' and rotate until the distance b/w them between them becomes 'y' ?

smogger9141 month ago

Well done! Thanks for the guide. Got it working in about 10 min.

smogger9141 month ago
mergavul2 months ago

Where do i connect power source/battery on this circuit.

i AM a student and i haven't any experienc in this field

please give me detailed circuit


These are your 2 power sources. Note that the USB jack should only be 5 volts! The DC jack has a voltage leveler that will convert anything from +5 volts - 9 volts to 5 volts. Anything over 5 volts can fry your boards! So, be careful!

F1T3TQ2H994BXMB.LARGE.jpg

The power should be connected to the Arduino. You can power it through USB from your computer, or from a 5 volt - 9 volt power supply (or a 9 volt battery with a DC jack adapter) through the DC jack on the board. Good luck!

JesseD10 made it!2 months ago

Eventually I'm gonna mount one of these babies on the front and back of my arduino controlled RC car. Just now, though, I set it up in front of the microwave in the kitchen. My unsuspecting roommates will get a nice little buzz in the dark when they walk into the kitchen! lol. Already got 2 of them with it! haha!

IMAG0148.jpgIMAG0146.jpgIMAG0147.jpg
Buhananberry3 months ago

Hi!

Could anyone please explain why this line:
distance = (duration/2) / 29.1;
...is true?

And what is that 29.1 number?

I know that distance = duration*velocity and it doesn't seem to be represented here.

Thanks

Example, if Δt = 500 microseconds, we know it took 250 microseconds for the ping to hit an object and another 250 microseconds to come back.

The approximate speed of sound in dry air is given by the formula:
c = 331.5 + 0.6 * [air temperature in degrees Celsius]
At 20°C, c = 331.5 + 0.6 * 20 = 343.5 m/s
If we convert the speed in centimetres per microseconds we get:
c = 343.5 * 100 / 1000000 = 0.03435 cm/ss
The distance is therefore, D = (Δt/2) * c
or D = 250 * 0.03435 = 8.6 cm

Instead of using the Speed of Sound, we can also use the "Pace of Sound".
The Pace of Sound = 1 / Speed of Sound = 1 / 0.03435 = 29.1 ss/cm
In this case the equation to calculate the distance become: D = (Δt/2) / Pace of sound
and for the example above: D = 250 / 29.1 = 8.6 cm

Hope this helps

akedia42 months ago

Hey, This was great help. Thanks!


However, I have a question about the use of the pulseIn function here. Aduino Documentauin tells me that this function starts timing when the pin gets a high signal, and then stops timing when the pin gets a low signal. So in our context it will record the ‘duration’ as the time between when it started hearing the reflected sound, and when it stopped hearing the reflected sound. But I don't think that is what we want. That duration will always be 10 microsecond, since that was the length of our pulse (assuming that any obstacle is further than 5 sound-microseconds). Don't we want something that starts timing whn the signal is first sent, and then stops timing when the signal is first received? I may be wrong. The code works perfectly, but it doesn't make theoretical sense to me.

I had the same question and here's what I found. Apparently the Echo side of the sensor produces a HIGH signal until it is interrupted when it senses the pulse. So the duration of the HIGH signal is indeed twice the time it takes for the sound wave to bounce off the object and make its way back to the Echo sensor. The interruption of the sound is what lasts for 10 microseconds... Hope tis helps
masyitaha4 months ago

hi,why does my sensor keep on telling out of range even when i'm putting obstacles in front of it.I'm using your code and circuit.

So I bought 4 of the HC-SR04 units from a place called robotshop.com, when I got them I opened one package and used a transducer and everything seemed okay. Today I used the exact same code and hooked up a second transducer and was getting some weird results; if either the emitter or receiver was occluded I wouldn't get any echo signal even after the obstruction was removed, if the unit did recover after the obstruction was removed it would take anywhere to a minute to start "working". It would also only "work" for a few seconds before not sending out an echo signal even if no obstruction had been introduced. BLARP!

I found a guy with a similar problem,

http://therandomlab.blogspot.com/2015/05/repair-and-solve-faulty-hc-sr04.html#comment-form

in the top photo he has the exact two flavors of the transducer I was sent; note the silk screen. The bottom transducer in the top image is the bad one ("Y1" on the silk screen under the crystal oscillator); I just happened to get two of each of the bad and good transducers.

I emailed robot shop and asked them to verify my findings and discontinue selling the faulty sensors. I also tried the resistor trick mentioned in the link I provided, but it didn't work very well. The sensor does immediately recover after an occluded emitter or receiver, but the range is now limited to only a few feet.

Hi

If you're sure from your wire connections & from non damage distance sensor you have, Try to make a rapid knock in front of the pulse source while it's working.
billtodd2 months ago

So I bought 4 of the HC-SR04 units from a place called robotshop.com, when I got them I opened one package and used a transducer and everything seemed okay. Today I used the exact same code and hooked up a second transducer and was getting some weird results; if either the emitter or receiver was occluded I wouldn't get any echo signal even after the obstruction was removed, if the unit did recover after the obstruction was removed it would take anywhere to a minute to start "working". It would also only "work" for a few seconds before not sending out an echo signal even if no obstruction had been introduced. BLARP!

I found a guy with a similar problem,

http://therandomlab.blogspot.com/2015/05/repair-and-solve-faulty-hc-sr04.html#comment-form

in the top photo he has the exact two flavors of the transducer I was sent; note the silk screen. The bottom transducer in the top image is the bad one ("Y1" on the silk screen under the crystal oscillator); I just happened to get two of each of the bad and good transducers.

I emailed robot shop and asked them to verify my findings and discontinue selling the faulty sensors. I also tried the resistor trick mentioned in the link I provided, but it didn't work very well. The sensor does immediately recover after an occluded emitter or receiver, but the range is now limited to only a few feet.

siluxmedia made it!1 year ago

Done it!
I've tested it comparing the measurements with millimeter paper, and i found that the value to divide is 36.9 instead 29.1 . That might depend on the sensor precision, I think.
The HC-SR04 can indeed be accurate between 2cm and 400cm, with a 0.3cm resolution over 1m and 1cm between 1m and 2m.
With less than 3cm the sensor gives a value over 3700, same if the two cilinders get covered.
It works perfectly against flat surfaces like walls, but lose precision over grass or other irregular surfaces.
Thanks for the tutorial!

IMG_20140506_153514.jpg

Thanks! I got 35 (roughly) indeed with measurement tape til 250cm. I've got 10 pieces, that yield very similar results, so there doesn't seem to be a big variance between devices.

Hopefully jsvestor can update the code example.

D6equj54 months ago

Re this HC-SR04 could anyone tell me what the two missing components are from my module? They are just behind the crystal and are stopping this module from working.

Thanks

D6

Image1.jpg

resisters

Nope, on my module these are two caps with 22pF, I think

BurakTutal4 months ago

Nice Project. I have made a smilar one. But mine is talking according to distance :) You can check my project. :)

http://www.instructables.com/id/Arduino-wtv020-Sd-...

D6equj5 made it!4 months ago

Nice little thing. The basics of a very useful tool for all sorts of projects.

2015-04-16 19.16.08.jpg

if the resistor i change to 330 ohm, will be trouble?

LostboyTNT5 months ago

/*I modded this for 1 LED, on pin 11 where it strobes faster or slower depending on distance*/

#define trigPin 13
#define echoPin 12
#define led 11
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
}
void loop() {
{
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 400 || distance <= 0){
Serial.println("Out of range");
distance = 400;
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(distance*8);
digitalWrite (led,HIGH);
delay(distance*8);
digitalWrite (led, LOW);
}
}

In your delay(distance*8)...what is the 8 and where did it come from.

Thanks

I don't remember exactly, I think it may have originally had something to do with the distance measure in centimeters (or similar), or it may have just been a number multiplier I picked that looked like a good delay. Sorry, wish I remembered.

1-40 of 158Next »