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");
<p>every time the output is displayed as out of range and if i modify <br>the code to measure distance its displayed as 0cm..whats the reason?</p><p>even<br> with the other code including the example code for ping sensors the <br>distanced is displayed as 0cm ...but with other arduino board the code <br>is working fine and the correct distance is being measured which implies<br> my sensor working fine...then wat may be the problem?</p>
<p>if i'll use arduino mega 2560, do the codes be the same? Please help. thank you.</p>
<p>Yes it will be same.</p>
<p>How could I get the my project specific details? How does paid membership work?</p>
Very nice tutorial. I like that I didn't have to download and install a new library into the Arduino libraries.<br>I made this with only one LED and resistor. I set it up to make the LED brighter the closer the object was to the sensor. LED on pin 6 (PWM type pin) on Arduino.<br>if (distance &gt; 0 &amp;&amp; distance &lt; 200) { //if distance is between 0 and 200<br> analogWrite(led, 255/distance); //use PWM to light the LED<br> }else{<br> analogWrite(led, 0); // if the distance is greater than 200 turn off the LED<br> }<br>
It shows pulseln not defined what should i do
<p>I ran into the same trouble. I changed it to read:</p><p>duration = pulseIn(echoPin, HIGH);</p><p>pulseIn, like pulse in and not LN.</p>
<p>how can you add more than one sensor, say like 5? Is there a limit to how many sensors you can have running at the same time, like there is with servos?</p>
<p>Using the general idea in his code, yes, you can add more sensors. If you can have them share the same pins, then there virtually no limitation (unless you start overwhelming your power supply). Otherwise, if you need them fully independent from one another, then you are limited by the number of digital I/O pins you have available.</p><p>Note that servos require a special kind of digital I/O pins, i.e. PWM (Pulse Width Modulation) capable pins. The HC-SR04 does not.</p>
<p>Just received the HC-SR04 and thanks to you I tested it :D</p>
<p>could you tell me from where you got the hc-sro4 part in fritzing? I am getting tired searching for it</p>
<p>can you help me ?</p><p>i want code arduino nano with buzzer conection it can you ?</p>
<p>Great ! Finally I got the Ultrasonic Sensor to work. Thank you for the tutorial. </p>
<p>possible give me code arduino nano conection with led :)</p>
<p>Thank u for this tutorial. Bu t i wanna ask u about the formula. Why the formula to find the distance is &quot;(duration/2/29.1)&quot;?</p>
<p>Thankyou so much for this great tuitorial. It worked great but the Echo and Trig wires have to be switched, as <u>AbhijitK24</u> said. I connected it up to my device and put the arduino ona portbale battery making it so I can move it around as needed, such as on an rc car.</p>
<p>Need a small edit. The code comment says <br></p><p>Echo to Arduino pin 13</p><p> Trig to Arduino pin 12</p><p>but the code itself uses (and this matches the Fritzing sketch)<br></p><p>#define trigPin 13<br><br>#define echoPin 12</p>
<p>Very Nice Tutorial!!</p><p>Works fine!!</p>
<p>Works very well even using my inexpensive NHduino Uno from china, when my cheep display arrives (<a href="http://www.ebay.co.uk/itm/381468326011?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT" rel="nofollow">For Arduino UNO/MEGA/Nano TFT Color Display Module Breakout SPI ST7735S 1.8 inch</a><br>) &pound;2.80 I'm going to try and have the display update with actual live distance :) Thanks for the cool info.</p><p>( 381468326011 )</p>
<p>Works great!</p>
<p>Can you please link us to that thing on which you have kept the arduino and the breadboard ?</p>
<p>Here is one: <a href="https://www.instructables.com/id/Acrylic-Arduino-Prototyping-Stand/" rel="nofollow">https://www.instructables.com/id/Acrylic-Arduino-Pr...</a></p><p>Or try searching for &quot;arduino holder&quot;.</p>
<p>Gr8 I'ble! I was trying to make an obtacle avoiding bot,but i had no idea how to code the HC-SR04 ultrasonic sensor.You saved my day!!</p>
<p>if want use ultrasonic sensor double. how do you do?<br>ทำไงงงงงงะ</p>
<p>Dude, this is awesome and I'm so thankful I found it and even more thankful you put this out on the site.. I'm going to use it to help us park our cars in the garage (pulling in the exact right distance). Thanks again!</p>
<p>Hi! Thanks for sharing! I'm new to arduino, and I'm having trouble. The green light goes on immediately and won't turn of, and the red light will not turn on. Can anyone advise me on what I might be doing wrong?</p>
<p>I triple-checked everything and I don't know what's wrong. I put in the code and built the circuit but when I run the program, it keeps displaying &quot;Out of range.&quot; Does anyone know why?</p>
<p>If you get out of range, first check layout of board and look for items that may be reflecting the sound very close to transmitter. Also, I notice a range error problem sensing flat objects with a surface oblique to the transmitter.</p>
Even i had same problem,Use an external 5v supply for ultrasnic sensor dont use arduino supply
<p>Hi,</p><p>How do I arrange an external supply. I am getting the same error</p>
<p>Thank you ,this project is very easy to build and understand</p>
<p>can somebody explain me the pulseIn() function. In the Arduino site they say pulseIn() function 'Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing'. So as they say it doesn't start timing when trigger signal is sent. rather it start timing when echo signal is initially get a signal. And stop timing when echo signal stop receiving waves. From that time measure can we calculate the distance as above equation?</p>
can anybody help me... im am really not good at this... i have a project and i really really need someones help.... please email me... science.140702487@gmail.com :`(
<p>Just hooked up my sensor following your tutorial, slightly modified. (No LEDs) And combined it with the &quot;Graph&quot; sketch to plot distance in Processing. Super simple! Thanks for a great and easily understandable tutorial!</p>
<p>I made this instructable and work's good </p>
<p>Hi, I followed and checked all connectins. But getting &quot;out of range&quot; repeatedly</p>
<p>i built this on an arduino mega.</p><p>i used, as recommended by some, a lab power supply on 3 and 5 volt, but it did not give good readings (out of range, wildly varying distances)</p><p>i had to exchange echo and trig. </p><p>i connected gnd and vcc of the hc-sr04 again to the arduino gnd and 5v.</p><p>now it works fine</p><p>thanks. </p>
<p>echo and trig pin arent declared in this scope</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>
Even i had same problem,Use an external 5v supply for ultrasnic sensor dont use arduino supply
<p>dude you need to make the arduino and the sensor communicate with each other, add the required driver and library updates to make that happen :) good luck </p>
<p>Sorry, but that doesn't make any sense to me. The HC-SR04 doesn't have a driver. </p><p>In the end, I just switched to the PING sensor. More expensive, but it works totally reliably.</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>Be sure the Echo and Trig are connected correctly. In the .txt file the header says one way but the actual pin definitions in the next section are backwards (12 and 13 are reversed)</p>
<p>Also check the specs on the HC-SR04 for which voltage is appropriate to use - I find mine works better on 3V instead of 5V</p>
<p>Thanks for the suggestions, Patrick. I verified that the Echo and Trig were correct. The spec says it takes 5V. I just tried it with an RFduino which puts out 3V, and still only saw zeros returning from the pulseIn function. I have gotten it to work with 5V, but I had to constantly disconnect and reconnect to reset it. I'm surprised more people haven't seen this -- I tried it with two different devices and had the same problem. I have had much better reliability with the PING sensor. I wish I could use it at 3V with the RFduino, but it doesn't seem to work reliably at that voltage. </p><p>Let me know if you have any other ideas.</p>

About This Instructable




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