Instructables

Simple Arduino and HC-SR04 Example

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.
josefsword12 hours ago

this is working thanks.

ahabib3 made it!yesterday

Thanks for sharing.

I did it without the leds

20140418_175038.jpg20140418_175032.jpg
made it, thanks
thassan316 days 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.

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

kubikus21 days 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?

waka20072 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)  waka200726 days ago

Glad to help.

macmac1822 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)  macmac18226 days ago

Thanks!

michaelhays1 month ago

Thanks! Works great.

jsvester (author)  michaelhays26 days ago

Thank you!

tpham23 made it!1 month ago

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

IMG_2637.jpg
jsvester (author)  tpham2326 days ago

Thank you. I'm glad it helped.

biomech751 month ago

nice!!

jsvester (author)  biomech7526 days ago

Thanks!

mwright3426 days 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
cpt13 months ago
Hi there, can you explain how you got 29.1?? Im doing a project with HC-sr04 and im using something like this distance = (duration/2) *0.034;
0,034 cm/us = 340,m/s

And btw thanks for this project and code. :D
waka2007 cpt11 month ago

so you are multiplying by 0.034 while the code is dividing my 29.1. They are simply inverse of each other.

haroldr2 months ago

When using this sensor, does it make a difference whether the object is soft clothing or a hard object?

It seems to me like it does...

jsvester (author)  haroldr2 months ago
When I was doing my testing, I did find a difference. I assumed it was because of the "bounce" off of the material.

Thanks for the question.
mgonos14 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)  mgonos13 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)

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

}

animes254 months ago
thanks for the instructable, I did a GoPro, Arduino and HC-SR04 project :D

http://www.instructables.com/id/GoPro-Ultrasonic-Motion-Sensor-HC-SR04-controled-b/
jsvester (author)  animes253 months ago

You're welcome! Cool idea with the GoPro.

waheedrafiq5 months ago
Thank you so much , I have search and search with dead ends , and finally someone has explain to me in basic term how to get HC-SR04 sensor working , thank you so much

jsvester (author)  waheedrafiq3 months ago

Glad to help!

mkohistani3 months ago

Hi there, thank you so much for this code. I have tried this 10 times, but I still get 0cm in my code. What could be the problem? All my settings and code are exactly like you - to the point that I used same colour coding of wiring... just to be safe.. I am new, please help :)

jsvester (author)  mkohistani3 months ago

Sorry to hear that you are having problems. Could you post your code? It is also possible you have a DOA sensor- which is why I made this simple setup.

daveclark57 months ago
thanks for taking the time to prepare this. i am trying to gang three of them together for a halloween scene control. the price on these overseas (< $2) is amazing so i had to try.
jsvester (author)  daveclark56 months ago
Glad to help. While this is my only Instructable so far, this site has given me many ideas and it's great to contribute.
Tony Gouveia6 months ago
Thanks, this is just what I was looking for.
jsvester (author)  Tony Gouveia6 months ago
Glad to help!
angpal596 months ago
I love it, I eliminated the resistors which make the LED's shine like a mo fo and might not last but it works perfectly, I would like to know if anybody else gets the same result as I do with the distance changed from 4 to 16 and get precisely 6.5 inches away. Also I am using arduino uno rev3
fgarci037 months ago
Thanks for the code!
I just got my Arduino today and I've been going nuts trying to get a code that worked with this sensor on Raspberry PI.

Now I finally managed to get something working.

Particularly like the "Serial monitor" distance measurer. You managed to put togrther on the same program both things I was meaning to try out!
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!