loading
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
  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);
}
<p>I didn't bother with the LED's and used a 16x2 display to display distance instead :) </p>
<p>when i go into the serial monitor it just says out of range over and over agin. can someone help?</p>
<p>i have 2 aduinos , mega and uno . i have an ultrasonic sensor . i want to record distance from the ultrsonic and send it via rf 433hz module to the recieve which will display the data on a 16x2 lcd . can some do the codes. i am new to programmig , and i need to submit my project . please </p>
<p>anyone that can help??</p>
<p>hey thanx man, i tweaked it and made a working parking indicator with leds switching off with length and increasing frequency of speaker with decrease in distance.</p>
<p>Worked great! Thank you very much for the information. It will be used for me to continue learning about arduino!! I plan on combining it with many other projects.</p>
<br><p>Ok thanks it works in a scketch alone but when i add engines nothing happens<br><br>I had to make a mistake but I'm starting and I'm not sure how to write the program.</p><p>I replaced the led by the engines?</p><p><br>Can you help me thanks</p><p>Cordially</p><p><br>#include &lt;Stepper.h&gt;<br><br>#include &lt;Ultrasonic.h&gt;<br><br>//#include &lt;Servo.h&gt; <br>#define trigPin 13<br>#define echoPin 12<br><br>//moteur droit<br>int L298N_IN1=9;<br>int L298N_IN2=8;<br>int L298N_ENA =2;<br>//moteur gauche<br>int L298N_IN3=7;<br>int L298N_IN4=6;<br>int L298N_ENB =3;<br><br><br>void setup() {<br> Serial.begin (9600);<br> pinMode(trigPin, OUTPUT);<br> pinMode(echoPin, INPUT);<br><br> <br>pinMode(L298N_IN1, OUTPUT);<br>pinMode(L298N_IN2, OUTPUT);<br>pinMode(L298N_IN3, OUTPUT);<br>pinMode(L298N_IN4, OUTPUT);<br> pinMode(L298N_ENA, OUTPUT);<br> pinMode(L298N_ENB, OUTPUT);<br>}<br> <br>void loop() {<br><br> long duration, distance;<br> digitalWrite(trigPin, LOW); // Added this line<br> delayMicroseconds(2); // Added this line<br> digitalWrite(trigPin, HIGH);<br>// delayMicroseconds(1000); - Removed this line<br> delayMicroseconds(10); // Added this line<br> digitalWrite(trigPin, LOW);<br> duration = pulseIn(echoPin, HIGH);<br> distance = (duration/2) / 29.1;<br> if (distance &lt; 4) { // This is where the LED On/Off happens<br> digitalWrite(L298N_IN1,HIGH); // When the Red condition is met, the Green LED should turn off<br> digitalWrite(L298N_IN2,LOW);<br> digitalWrite(L298N_IN3,HIGH);<br> digitalWrite(L298N_IN4,LOW);<br>}<br> else {<br> digitalWrite(L298N_IN1,LOW);<br> digitalWrite(L298N_IN2,HIGH);<br> digitalWrite(L298N_IN3,LOW);<br> digitalWrite(L298N_IN4,HIGH);<br> }<br> if (distance &gt;= 200 || distance &lt;= 0){<br> Serial.println(&quot;Out of range&quot;);<br> }<br> else {<br> Serial.print(distance);<br> Serial.println(&quot; cm&quot;);<br> }<br> delay(500);<br><br> digitalWrite(L298N_ENA, HIGH);<br> digitalWrite(L298N_ENB, HIGH);<br> <br> <br>startCar();<br>delay(1000);<br>stopCar();<br>delay(1000);<br>leftTurn();<br>delay(1000);<br>rightTurn();<br>delay(1000);<br><br>}<br><br>void startCar()<br>{<br> <br> digitalWrite(L298N_IN1, HIGH);<br> digitalWrite(L298N_IN2, LOW);<br> digitalWrite(L298N_IN3, HIGH);<br> digitalWrite(L298N_IN4, LOW);<br>}<br>void stopCar()<br>{<br>digitalWrite(L298N_IN1, LOW);<br> digitalWrite(L298N_IN2, LOW);<br> digitalWrite(L298N_IN3, LOW);<br> digitalWrite(L298N_IN4, LOW);<br><br>}<br>void leftTurn()<br>{<br>digitalWrite(L298N_IN1, LOW);<br> digitalWrite(L298N_IN2, HIGH);<br> digitalWrite(L298N_IN3, HIGH);<br> digitalWrite(L298N_IN4, LOW);<br><br> }<br> void rightTurn(){<br><br> <br>digitalWrite(L298N_IN1,HIGH );<br> digitalWrite(L298N_IN2, LOW);<br> digitalWrite(L298N_IN3,LOW );<br> digitalWrite(L298N_IN4, HIGH);<br> }</p>
<p>Works great. I just bought a 5 pack of these from Amazon for a song. I followed your instructions and it works great. One question though, you changed a few things in the code (specifically the delayMicroseconds(1000)) and added much lower delay values elsewhere. Why these changes? What did you fix with these changes?</p>
<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>ok</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>ok</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>ok</p>
<p>if want use ultrasonic sensor double. how do you do?<br>ทำไงงงงงงะ</p>
<p>ok</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>

About This Instructable

987,731views

330favorites

License:

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