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.
1-40 of 67Next »
Rowski1 month 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);
}

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

}

VladStancu1 month 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!1 month 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
ppatchen2 months ago

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

Thanks!

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

josefsword3 months ago

this is working thanks.

ahabib3 made it!3 months ago

Thanks for sharing.

I did it without the leds

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

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

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

waka20075 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)  waka20074 months ago

Glad to help.

macmac1825 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)  macmac1824 months ago

Thanks!

michaelhays5 months ago

Thanks! Works great.

jsvester (author)  michaelhays4 months ago

Thank you!

tpham23 made it!4 months ago

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

IMG_2637.jpg
jsvester (author)  tpham234 months ago

Thank you. I'm glad it helped.

biomech754 months ago

nice!!

jsvester (author)  biomech754 months ago

Thanks!

mwright344 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
cpt16 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 cpt15 months ago

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

haroldr5 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)  haroldr5 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.
animes258 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)  animes256 months ago

You're welcome! Cool idea with the GoPro.

waheedrafiq9 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)  waheedrafiq6 months ago

Glad to help!

mkohistani6 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 :)

1-40 of 67Next »