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

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
  else {
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  else {
    Serial.println(" cm");
Thanks! Now the kids habe to wait at the slide in the children room ;)
<p>instead of wasting power, by keeping one led on always... 1 led which glows when the object comes near is a better approach. Here is the code for that :-</p><p>void setup() {</p><p> Serial.begin (9600);</p><p> pinMode(trigPin, OUTPUT);</p><p> pinMode(echoPin, INPUT);</p><p> pinMode(led, OUTPUT);</p><p>}</p><p>void loop() {</p><p> long duration, distance;</p><p> digitalWrite(trigPin, LOW);</p><p> delay(1)</p><p> digitalWrite(trigPin, HIGH);</p><p> delay(5)</p><p> digitalWrite(trigPin, LOW);</p><p> duration = pulseIn(echoPin, HIGH);</p><p> distance = (duration/2) / 29.1;</p><p> if (distance &lt; 10) {</p><p> digitalWrite(led, LOW);</p><p> }</p><p> else{</p><p> digitalWrite(led, HIGH)</p><p> }</p><p> if (distance &gt; 200){</p><p> Serial.println(&quot;Out of range&quot;);</p><p> }</p><p> if (distance &lt; 0){</p><p> Serial.println(&quot;Out of Range&quot;)</p><p> }</p><p>}</p>
<p>Great example ! I suggest getting rid of the floating point math. I tested both ways</p><p>and saved 500 bytes of program space doing away with the floating point.</p><p>How about scaling up by 10 to get rid of 29.1 (becomes 291). </p><p>distance = ( (distance &gt;&gt;1) *10)/291;</p><p>// (distance &gt;&gt;1) is division by two</p>
<p>Very nice !</p>
<p>Thanks for writing this up - worked like a charm. Minor code suggestion : </p><p>int ledState = distance &lt; 4;</p><p>digitalWrite(led, ledState);</p><p> digitalWrite(led2, !ledState);</p><p>can replace - </p><p>if (distance &lt; 4) { // This is where the LED On/Off happens<br> digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off<br> digitalWrite(led2,LOW);<br>}<br> else {<br> digitalWrite(led,LOW);<br> digitalWrite(led2,HIGH);<br> }</p>
great instruction! Can't wait to use it
<p>This worked very well! I have one question though: </p><p>Where does this line come from in the code -</p><p> distance = (duration/2) / 29.1;</p><p>I get that the duration is divided by two to account for the echo. I can't figure out where the 29.1 comes from though. Any thoughts?</p>
<p>Dividing it by 29.1 makes the distance value equal to centimeters instead of whatever it would originally be. Hope this helps. :D</p>
<p>BEER THEFT ALARM!!! I modified this project slightly to make a beer theft alarm as demonstrated in the video. Just added a 1.5V buzzer between the red LED anode and GND. :-D</p>
<p>Merci Beaucoup ca a fonctionn&eacute; du premier coup, super bien r&eacute;alis&eacute; votre tuto.</p>
<p>Just started with Arduino and this is extremely helpful, I have a PING sensor with only three connections, a ground, 5v and a SIG (signal) input / output. How would I modify the code for this? </p>
<p>you didn't specify which sensor you have, but there's a &quot;ping&quot; sketch for a three pin version under the File-&gt;examples-&gt;&quot;sensors&quot; in the arduino software that might serve your purposes.</p>
<p>Thxiu, very usefull</p>
<p>Thanks !!! Very cool example and easy to follow for beginners.</p><p>Can't wait to play with it some more :)</p>
<p>the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.</p><p>A working code:</p><p>#include &lt;NewPing.h&gt;</p><p>#define TRIGGER_PIN 12</p><p>#define ECHO_PIN 11</p><p>#define MAX_DISTANCE 200</p><p>NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);</p><p>void setup() {</p><p>Serial.begin(9600);</p><p>}</p><p>void loop() {</p><p>delay(50);</p><p>unsigned int uS = sonar.ping();</p><p>pinMode(ECHO_PIN,OUTPUT);</p><p>digitalWrite(ECHO_PIN,LOW);</p><p>pinMode(ECHO_PIN,INPUT);</p><p>Serial.print(&quot;Ping: &quot;);</p><p>Serial.print(uS / US_ROUNDTRIP_CM);</p><p>Serial.println(&quot;cm&quot;);</p><p>}</p><p>link: <a href="http://forum.arduino.cc/index.php?topic=55119.15" rel="nofollow">http://forum.arduino.cc/index.php?topic=55119.15</a></p><p>NewPing link: http://playground.arduino.cc/Code/NewPing</p>
<p>You're awesome. This is exactly the solution I was looking for.</p>
you're awesome too :) . glad i could be of assistance.
<p>Very nice explanation. worked like a charm!</p>
<p>Very nice explanation. worked like a charm!</p>
<p>Very nice explanation. worked like a charm!</p>
<p>Hello, I would like to know what kind of formula you used to calculate the distance. What is the 29.1? </p><p>The &quot;<br>duration = pulseIn(echoPin, HIGH);<br>distance = (duration/2) / 29.1; &quot; part.</p><p>Thank you.</p>
<p>The speed of sound is approximately 29.1 microseconds per centimetre. This converts the echo time to centimetres.</p>
<p>I'm new to Arduinos, but have done other hardware projects. I followed the instructions, but I am always seeing &quot;Out of range&quot;. I modified the code to see what distance it thought it was seeing, and it is always zero. Any suggestions on how to debug this?</p>
I have seen this same issue with mine. Constantly seeing zero. Make sure all your inputs are defined and are landed on the correct pins. Also make sure your trigger and your Echo are not switched around. I have code for what I did because I kept getting it to stick on zero and needed to unplug the sensor for it to work unless I put my finger on the left upper corner of the hc Hr04. So I ended up making and input that when it senses 0 it will set this pin to high then low. I will upload more later for people having problems. My way seemed to fix it getting stuck on 0
<p>I also got it to work by unplugging the sensor and plugging it back in again. Which pin did you set to high and then low to get it to work?</p>
<p>I'm recently entering the world of Arduino. I have to thank you very much for this tutorial, I just made it and it works, my first &quot;project&quot; with my Arduino UNO, I just want to know if anyone can help me to understand the code, because I only copied it and ran it, I want to understand it, is there any tutorials that anyone recommend for begin to program in Arduino?</p>
<p>I have never done anything with Arduinos before. I have a drone. It's a DJI Phantom 2 Vision Plus. I plan on using this sensor with a nano Arduino to automate a retractable landing gear. When the quad is less than 5 feet off the ground the gear will come down. Anything over 5 feet and the gear will go up. Like I said I have never done anything with Arduinos before. I ordered some stuff off of Ebay and found this page. This was exactly what I needed. 2 hours of play time and I have this set up on my desk looking out horizontally. I push my desk chair up to the sensors and they reliably trigger at about 5 feet. That is with a value of 120 where the author originally had 4. this is great and very promising. I am stoked! thank you. </p>
I have a challenge for you to try. Could the Arduino Be made to act like a k2 metre.
<p>Thanks for the instructions. It was exactly what I needed to test the sensors I got off ebay. Thanks to your tutorial I was able to discover one sensor was broken. Without this I would've probably thought it was due to an error on my part.</p>
<p>Very helpful instructable for a part that often doesn't come with any information other than the circuit board.</p>
<p>Great quick project. Same situation as you, just wanted to confirm function before getting into any detailed work. Worked perfect five minutes after finding your Instructable. Does it get any easier than that??? </p>
Can the Arduino be made to act like a k2 metre.
<p>This was very helpful in making my prototype parking sensor, thank you!</p>
<p>Great tutorial. Thanks!</p>
<p>hola, como puedo a&ntilde;adir una matrix de dos colores en vez de dos led, la matrix dira en color verde siga y la roja Pare.</p>
<p>Hi</p><p>Im trying to replicate the ''Arduino Tone 3'' tutorial, except replacing the 3 force sensors with 3 HC-SR04's.</p><p>can this be done?</p><p>would be great to hear some ideas</p>
<p>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.</p>
<p>thanks </p>
<p>Thanks, worked first time!</p>
<p>Hy.</p><p>my name is abdu</p><p>thnx 4 ur every replies</p><p>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..?</p><p>would you please give me detailed <strong>circuit diagram </strong>and its <strong>code.</strong></p>
<p>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.</p><p>Here is video showing an example of sensing distance. Code is given by the fellow who made the video (not me.)</p><p>here is some non-function code:</p><p>loop(){</p><p>static int far_away=0;</p><p>static int motor_on=0;</p><p>far_away=verify_distance(); //this function returns 0 when too close, else 1.</p><p>motor_on=0; //play it safe, with the default being the motor is off.</p><p>if( far_away ){</p><p>motor_on=1;</p><p>}</p><p>my_pin=activate_motor(motor_on);</p><p>set_output_pin(my_pin); //view motor state</p><p>sleep(1 second);</p><p>}</p><br><p><iframe allowfullscreen="" frameborder="0" height="281" src="//www.youtube.com/embed/7ZPc__5tL3c" width="500"></iframe></p>
<p>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' ?</p>
<p>Well done! Thanks for the guide. Got it working in about 10 min. </p>
<p>Where do i connect power <strong>source/battery</strong> on this circuit.</p><p>i AM a student and i haven't any experienc in this field </p><p>please give me detailed circuit</p><p><strong><br></strong></p>
<p>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!</p>
<p>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!</p>

About This Instructable


238 favorites


More by jsvester: Simple Arduino and HC-SR04 Example
Add instructable to: