Instructables
loading
loading
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 130Next »
siluxmedia made it!11 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

Thanks! I got 35 (roughly) indeed with measurement tape til 250cm. I've got 10 pieces, that yield very similar results, so there doesn't seem to be a big variance between devices.

Hopefully jsvestor can update the code example.

D6equj51 month ago

Re this HC-SR04 could anyone tell me what the two missing components are from my module? They are just behind the crystal and are stopping this module from working.

Thanks

D6

Image1.jpg

resisters

Nope, on my module these are two caps with 22pF, I think

BurakTutal25 days ago

Nice Project. I have made a smilar one. But mine is talking according to distance :) You can check my project. :)

http://www.instructables.com/id/Arduino-wtv020-Sd-...

masyitaha1 month ago

hi,why does my sensor keep on telling out of range even when i'm putting obstacles in front of it.I'm using your code and circuit.

D6equj5 made it!1 month ago

Nice little thing. The basics of a very useful tool for all sorts of projects.

2015-04-16 19.16.08.jpg

if the resistor i change to 330 ohm, will be trouble?

LostboyTNT2 months ago

/*I modded this for 1 LED, on pin 11 where it strobes faster or slower depending on distance*/

#define trigPin 13
#define echoPin 12
#define led 11
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, 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 >= 400 || distance <= 0){
Serial.println("Out of range");
distance = 400;
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(distance*8);
digitalWrite (led,HIGH);
delay(distance*8);
digitalWrite (led, LOW);
}
}

In your delay(distance*8)...what is the 8 and where did it come from.

Thanks

I don't remember exactly, I think it may have originally had something to do with the distance measure in centimeters (or similar), or it may have just been a number multiplier I picked that looked like a good delay. Sorry, wish I remembered.

Haha, no worries was still a big help and it worked so thanks.
rkasemi8 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!!!

HI, i developed this with sensor and hub-ee wheels. Here is a video and all my code. Have fun :)

IMG_0332.MOV.mov(402x714) 24 KB

We are making something very similar but were wondering how you stabilized the sensor on the front of the cart

EdizonBlu1 month ago

Hello sir, i added this code and applied it with servo motor. I mounted the ultrasonic sensor on the servo motor. But i have a problem, I would like to ask on how to stabilize my ultrasonic sensor mounted in a servo motor. It is because everytime an "Out of Range" displays in the serial monitor it gives current to the servo motor causing it to sweep. The possibility of sweeping the servo left or right only is when there is an object being detected.

.

Here is my code://

#define trigPin 13

#define echoPin 12

#define led 11

#define led2 10

#include <Servo.h>

int pos = 0; // variable to store the servo position

int defPOS = 0;

Servo myservo;

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(led, OUTPUT);

pinMode(led2, OUTPUT);

myservo.attach(9);

myservo.write(0);

}

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;

//0 Left

//1 Center

//2 Right

int buttonState1 = digitalRead(led); //red

int buttonState2 = digitalRead(led2); //green

if( (buttonState1 == 0 && buttonState2 == 1) && (defPOS != 1))

{

delay(2000);

if(defPOS == 2)

{

for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(2); // waits 15ms for the servo to reach the position

}

}

else if(defPOS == 0)

{

for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(2); // waits 15ms for the servo to reach the position

}

}

defPOS = 1;

}

if (distance < 30) { // 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(defPOS == 0)

{

for(pos = 90; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees

{

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(2); // waits 15ms for the servo to reach the position

}

defPOS = 2;

}

else if(defPOS == 2)

{

for(pos = 0; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(2); // waits 15ms for the servo to reach the position

}

defPOS = 1;

}

else if(defPOS == 1)

{

for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree

myservo.write(pos); // tell servo to go to position in variable 'pos'

delay(2); // waits 15ms for the servo to reach the position

}

defPOS = 0;

}

//myservo.write(180);

// delay(1000);

//myservo.write(0);

}

else {

digitalWrite(led,LOW);

digitalWrite(led2,HIGH);

}

if (distance >= 400 || distance <= 0){

Serial.println("Out of range");

}

else {

Serial.print(distance);

Serial.println(" cm");

}

delay(500);

}

How can I add a motor which will start rotating if the distance b/w the sensor and any object is 'x' and rotate until the distance b/w them between them becomes 'y' ?

hai..i tried your code for 2 leds (red and green). but while compiling i got an error message saying "pulseln() was not declared in the scope". what should i do?

Hai..i tried your code for 2 leds (red and green). but while compiling i got an error message saying "pulseln() was not declared in the scope". what should i do?

hai..i tried your code for 2 leds (red and green). but while compiling i got an error message saying "pulseln() was not declared in the scope".

what should i do?

JohnC332 months ago

This turned out to be very easy. The instructions were very clear and the code is simple enough. I'm now incorporating this into a robot that will avoid obstacles. Thanks so much for helping me get started.

John

majd.kasawat made it!2 months ago

working in less than 5 minutes

IMG_20150312_005910.jpg
Jose E.G2 months ago

I Made it!!! Thanks . I was thinking the sensor was damage. Really appreciate your time to teach a beginner. Very helpful and easy

abdul.sami.752 months ago

the green led just blink wid the tx led

abdul.sami.752 months ago

it didnt work for me

abdul.sami.752 months ago

it doesnt work for me y?

kumarsrt2 months ago

hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors

Not sure as far as the voltage matters, but I think if it's within the power draw specs, shouldn't matter where the supply voltage for the sensors comes from, the data pins should still "ping" and "listen"
when using multiple sensors, make sure and put a delay of about 40 ms between each sensor, or you may wind up getting a 'false echo' from one of the other sensors, also even though they're 'rated' for 15 degrees, you probably want to put a minimum of 30 degrees rotation between them, and put a 'timeout' on the read, or a lost echo will be delaying a full second waiting. from reading another article, "put a timeout on the pulseIn, like ... pulseIn(echoPin , HIGH , 9000 ) ; where 9000 is 9000 microseconds or 9 milliseconds, which works out to about 150cm or 5feet (speed of sound, travels distance twice, lots of maths)."
Hope this helps

KenL43 months ago

Thanks, I brought 10 sensors for a few project and this was the fastest way to test it. They all work, and thanks again for such a easy to follow example.

Blazingnite3 months ago

what does the || mean?

|| means "OR". As in this OR that.

so

if (distance >= 200 || distance <= 0){

Serial.println("Out of range");

is saying if the distance is greater than or equal to 200 OR the distance is less than or equal to 0, then print the line "Out of range"

on that same note, if you see &&, that means AND

Trippme3 months ago

Very simple, thank you!

baudeagle3 months ago

Thank you very much, helps me to test my new ultrasonic sensors from Ebay.

RobL13 months ago

followed the instructions and had it working in minutes - great directions, thanks very much...now to try with a Picaxe!

cheers

Rob

menandroi3 months ago

my another question is what is this value ? ---> distance = (duration/2) / 29.1;

menandroi3 months ago

what if there are 3 different alarm? for example 25cm to 50cm will trigger alarm1, 51 to 75cm alarm2 and 76 to 100cm above for alarm3? what is the command to be used?

menandroi3 months ago

what if there are 3 different alarm? for example 25cm to 50cm will trigger alarm1, 51 to 75cm alarm2 and 76 to 100cm above for alarm3? what is the command to be used?

rituchoudhary made it!3 months ago

Thanks for sharing the tutorial. :-)

IMG-20150205-WA0012.jpeg
eranox made it!3 months ago

This is just what I was looking for! Thanks for such a detailed, straighforward instructable. This will come in handy in dozens of projects!

20150204_134035[2].jpg
1-40 of 130Next »