Instructables
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.
 
Remove these adsRemove these ads by Signing Up

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.
1-40 of 86Next »
tagr made it!8 days ago

I just try this tutorial , it's working . it's really useful for me. thanks for sharing.

8828.jpg8829.jpg
schulbusl10 days ago

thanks for the tutorial,

my version of it :D

IMG_20141207_040152.jpg

I can't seem to green LED to light up and I'm pretty sure that I've wired it up correctly.
If I keep an object at a distance less that 4cm, the red LED lights up just fine though.

mcansozeri made it!27 days ago

Thanks for the tutorial. It was really helpful for me. I'll improve this and share it with you :D

image1 (1).JPG
bochokoy27 days ago

I tweaked this.. I added a DC Motor in the circuit. Everytime the sensor detects an object the DC Motor wont start though, it rotates when spinned manually. Could somebody help me with this? It's like the voltage is too low. Im having Arduino Nano. Help? anyone

Boba_Steph made it!3 months ago

Made it!

Very helpful for a beginner like me. Now I'm currently working on adding a speaker that will change in tone as distance increases.

HCSR04.jpg

hey, I'm trying to do a similar thing with changing volumes, could i ask how you're going about it?

You can use piezo beep to make frequency-varying speakers :)

thanks, I'm trying to change an mp3 though

CarlosV21 month ago

very good, Thanks

salman473 months ago

first i made it.. but when i tried it to
show some friends.. the hc sr04 sensor stopped working its consistantly
giving "out of rang" in serial monitor :( .. in addition my Tx LED of arduino Mega keep blinking when i upload the code in it now ..

ErwinC salman472 months ago

Me too, and after double-checking, the blue and green wires were swapped and after fixing that it all worked great.

Maybe cause this line is swapped.

"Echo to Arduino pin 13 Trig to Arduino pin 12"

Should say, Echo to 12 and Trig to 13.

agrove33 months ago

Nice article! I found a nice tutorial on HC-SR04 and Arduino here as well: http://superawesomerobots.com/tutorials/hc-sr04-tutorial-for-arduino/

jaimeiniesta3 months ago

Made it!

Thanks, this was easy to setup. I've seen there are libraries to make this easier, though:

http://playground.arduino.cc/Code/NewPing

MattS33 months ago

Hi wonderful model, but I'm having trouble getting the LEDs to blink even though the sensor unit is picking up and the breadboard receiving data. Might you have the answer?

Great and simple

RittaChickka3 months ago
rkasemi3 months ago

i need to make a obstacle avoiding robot and i have a HC-SR04 sensor, can anyone help me to modify this code because i need to put servo motors instead of lights, plzzz i need your help!!!

Rowski6 months ago

excellent work. I experimented and made this into a basic reversing sensor with a piezo buzzer added to led HIGH output and GND.
This sample will alert you as you aproach 1.5mtrs and flashes the LED and beeps quicker as you get to 50cm. after that it is constant .

#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, alert;
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;
alert = (distance*4);



if (distance < 150) { // 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);
delay(alert/4);
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}

else {

digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}

if (distance < 50) { // 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);
}

if (distance >= 0 || distance <= 150){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
Serial.print("\t Alert time ");
Serial.print(alert);
Serial.println(" ms");
}
delay(alert/2);
}

mgonos11 year ago
Thanks for the idea, This is a great way to learn the fundamentals of HC-SR04 sensors. I added a peizo which makes an alarm sound when "red" condition is met.


#include

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10
#define ALARM 9
#define led3 6
int switchState = 0;
float sinVal;
int toneVal;
int notes[] = {15};
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(ALARM, OUTPUT);
pinMode(by2,INPUT);
pinMode(led3,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 < 4) { // This is where the LED On/Off happens
digitalWrite(led,HIGH);
delay (100);
digitalWrite(led3,HIGH);
delay (100);
digitalWrite (led,HIGH);
delay (100);
digitalWrite(led3,HIGH);
delay (100);// When the Red condition is met, the Green LED should turn off
digitalWrite(led,LOW);
digitalWrite (ALARM,HIGH);
for (int x=0; x<180; x++){///creates an alarm like sound for peizo
sinVal = (sin(x*(3.1412/200)));
toneVal = 2000+(int(sinVal*1000));
NewTone(ALARM, toneVal);



}
}
else {
delay (50);
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
digitalWrite(led3,LOW);

digitalWrite (ALARM,HIGH); // This statement will make The Peizo be quiet when condition is not met
for (int x=0; x<180; x++){///test
sinVal = (sin(x*(3.1412/180)));
toneVal = 0;
NewTone(ALARM, toneVal);

}
//digitalWrite(ALARM,LOW);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
digitalWrite (led3,HIGH);
digitalWrite (led2,LOW);
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
jsvester (author)  mgonos111 months ago

Thanks! Great idea for the audio alarm. One of the great things about the Arduino is how easy it is to stack ideas.

By the way, I have tried two HC SR04 sensors, I have 8 of them, I can try them all... (don't ask why I have 8 hehe - I bought them cause I thought one was dead and it's a handy thing to have)

can you please post the code for 8? :D i am using 7 and i have some issues with the code. thanks!

Thank you SO much for replying back. I have followed everything of your code & instructions then wrote my own code a bit, it's just not working :( is it the sensor, I can't figure out. The serial monitor screen keeps saying 0cm every second.

Here is my sensor details:

http://www.ebay.com/itm/2pcs-HC-SR04-Ultrasonic-Mo...

This is my code try 1:

#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);

}

This is my code try 2:

#define trigPin 3

#define echoPin 2

#define digPin12 12

void setup(){

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin,INPUT);

pinMode(digPin12, OUTPUT);

}

void loop(){

int duration, distance;

digitalWrite(trigPin, HIGH);

delayMicroseconds(1000);

digitalWrite(trigPin, LOW);

duration= pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

Serial.print(distance);

Serial.println(" cm");

digitalWrite(digPin12, HIGH);

delay(500);

}

VladStancu6 months ago

Can somebody help me please.. I have 7 HC-SR04 sensors and I am using an arduino micro and I have 2 major issues: 1) do i have to supply power to the arduino and sensors separately or not (examples would help) and also 2) I am a beginner and I have some problems with the codding for the project. Can somebody help?

siluxmedia made it!6 months 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
ppatchen7 months ago

I'm totally late to the party but this works great!

Thanks!

Rocker5177 months ago

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException

at processing.app.Editor.checkModified(Editor.java:2025)

at processing.app.Base.handleClose(Base.java:758)

at processing.app.Editor$1.windowClosing(Editor.java:164)

at java.awt.AWTEventMulticaster.windowClosing(AWTEventMulticaster.java:332)

at java.awt.AWTEventMulticaster.windowClosing(AWTEventMulticaster.java:332)

at java.awt.Window.processWindowEvent(Window.java:1862)

at javax.swing.JFrame.processWindowEvent(JFrame.java:279)

at java.awt.Window.processEvent(Window.java:1820)

at java.awt.Component.dispatchEventImpl(Component.java:4630)

at java.awt.Container.dispatchEventImpl(Container.java:2099)

at java.awt.Window.dispatchEventImpl(Window.java:2475)

at java.awt.Component.dispatchEvent(Component.java:4460)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

This thing came up. Any suggestions?

I am using the Arduino UNO and the official IDE.

josefsword8 months ago

this is working thanks.

ahabib3 made it!8 months ago

Thanks for sharing.

I did it without the leds

20140418_175038.jpg20140418_175032.jpg
bayarfaj20048 months ago
made it, thanks
thassan38 months ago

how can make this project to a robot by adding two/four wheel?
then what will be the code. plz let me know soon as I have to submit a project abt this within this week.

mwright348 months ago
this is quite frustrating
jsvester (author)  mwright348 months ago

I am not sure what could be causing that error. One of the purposes of this instructable is to test for DOA sensors. You might have a damaged HC-SR04 on your hands. If you find a solution, please post back to help others troubleshoot.

iI have two of these sensors and I am truly baffled as to why I cant seem to get any code to work. I have tried many codes to no avail. but if I happen to find the issue I will let you know. I am thinking of going to a 3 prong ultrasonic sensor. the price is higher, and they seem to have codes on the arduino.cc site. thanks for your help.

The standard example sketch in the Arduino IDE works for my HC-SR04. Check the components with a magnifying glass, possible a solder came lose on one of the little surface mount parts. I ordered two HCSR04 and one of them I noticed immediately that on the back R1 (resistor I believe) had broken off from the solder on one side so I never used it. My other one is fine and works as I tested it with the serial monitor.

kubikus8 months ago

The trigger pin of my sensor is constantly at +5V. But this is supposed to be an input. I guess my sensor is broken?

waka200710 months ago

Thank you so much for this code!!! I just got my sr04 and this code helps so much in learning how it works.

1-40 of 86Next »