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.

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 76Next »
salman4723 days 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 ..

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.

Boba_Steph made it!5 days 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
agrove36 days 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/

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

MattS311 days 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

rkasemi23 days 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!!!

Rowski3 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);
}

mgonos19 months 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)  mgonos18 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);

}

VladStancu3 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!3 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
ppatchen4 months ago

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

Thanks!

Rocker5174 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.

josefsword5 months ago

this is working thanks.

ahabib3 made it!5 months ago

Thanks for sharing.

I did it without the leds

20140418_175038.jpg20140418_175032.jpg
bayarfaj20045 months ago
made it, thanks
thassan35 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.

mwright345 months ago
this is quite frustrating
jsvester (author)  mwright345 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.

kubikus5 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?

waka20077 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.

jsvester (author)  waka20075 months ago

Glad to help.

macmac1827 months ago

Code works great. However, I used the sketch's text to wire it up and found you have the Trig and Echo swapped. "Echo to Arduino pin 13 Trig to Arduino pin 12."

jsvester (author)  macmac1825 months ago

Thanks!

michaelhays6 months ago

Thanks! Works great.

jsvester (author)  michaelhays5 months ago

Thank you!

tpham23 made it!6 months ago

exactly what i was looking for ! you're awesome!

IMG_2637.jpg
jsvester (author)  tpham235 months ago

Thank you. I'm glad it helped.

biomech756 months ago

nice!!

jsvester (author)  biomech755 months ago

Thanks!

mwright345 months ago
i tried to use this code and i get an error cod that says that the command long distance, duration has not been declaired how do i fix this
1-40 of 76Next »