Introduction: Simple Arduino and HC-SR04 Example

Picture of Simple Arduino and HC-SR04 Example

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.

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

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

Comments

NikonUser (author)2017-10-10

I've purchased the sonic sensor along with a 4 digit 7-segment LED, and am planning to use this idea as a gauge for my rainwater tank. Knowing the depth of the water surface below the top of the tank, I can work out the remaining capacity and display it on the LED either as the number of litres left, or more likely I'll just display it as a percentage. I think 65% is more immediately meaningful than knowing I have 1137 litres

Still waiting for my gear to arrive, so am intrigued to know the accuracy of this device, but will probably dumb it down to 5% increments anyway for the display.

Thanks for providing a good grounding to understand the connection and operation of the unit.

smj135 (author)NikonUser2017-11-30

I don't know if you'll see this comment, but maybe try checking out "level switches". Essentially it's a reed sensor that can be mounted inside of a container with liquid. They have to be mounted by drilling a bit in the container, don't know if this will be an issue for you. try this link to see what i'm talking about:

https://www.ebay.com/itm/5-Level-Switches-Liquid-L...

NikonUser (author)smj1352017-12-01

Thanks for the idea - but access into the rainwater tank is very limited via a single 30cm diameter hole in the top, and I don’t really want to start drilling holes and have to seal them (a disaster just waiting to happen!!), but the good news is that I have been able to build and test my unit - at least on breadboard (haven’t had time to mount it in a box yet), and all works to my satisfaction. The next step is to make all the connections permanent on my pro-mini, and drill the correct size holes in the box for the sensors to poke through. Btw - very impressed with the accuracy of the unit considering it was a cheap Chinese clone from eBay - it was good to within 1-2cms at 4 metres, and <1cm error at 2 metres. More than adequate for my needs.

jlourenço1 made it! (author)2017-11-30

thanks!

shakthik92 made it! (author)2017-10-20

Thanks... I used Buzzer too...

mikey_lambert (author)2017-04-15

Hi there,

I'm doing something similar to this for a school project. I have three SR04s (and will eventually have three LEDs). I've hooked up one LED, to turn on when something is within a certain range of sensor 0. I've debugged the code and the LED turns on when it should, but it's REALLY dim. You wouldn't even notice if you weren't looking for it. That's without even having a resistor in the LED circuit (which I know isn't recommended, but with a resistor, the LED probably wouldn't even turn on). I'm assuming the amount of current is the issue - is this due to having so many sensors? Do you have any suggestions for increasing the current in the LED?

Many thanks.

ThomasW165 (author)mikey_lambert2017-10-14

Be sure you do a pinMode(pin, OUTPUT); or LEDs can look very dim like that. Don't forget a 220ohm current limiting resistor!

NikonUser (author)mikey_lambert2017-10-10

Hi Mikey - IF that is the reason for your LEDs being dim (sounds a reasonable hypothesis), then instead of using the xxduino outputs to directly drive the LEDs, you could use them to drive transistors instead, and have them switch the LEDs on or off while being driven from the power supply rather than relying on the xxduino's limited current provision.

happyman1111 (author)2017-06-26

first, am say thank you very much for make this jsvester! you are saver of lifes!!!!

i have had to be having doing school assignment big one for end of year and i forgetting how to do this!!!!!!! quick and good guide you helping me very much i am super greatful you make my pass my year now i have 55% !!!!!!!!!!!!

give me your paypal email and i will donating you to donate to give you money to support more guide!!!!! 2 DOLLARS for you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

misterxp (author)2017-06-10

Great for testing device thanks!

NeepaB (author)2017-05-12

Can someone please upload the circuit diagram for this example. Thank you in advance.

Strato_caster (author)2017-05-02

Works great. Thanks! It Would be great to have a string of these and make them addressable(reverse). so you can figure out which one triggered. Something like the NeoPixel led strip where you can turn on a specific led in the strip, but in this case in reverse.

HendrikB7 (author)2017-04-30

Just a question about declaring the distance.

As indicated below I would like to have it operate as close to the maximum distance of 400cm or 450cm. However I`m not sure about the code setting the distance;

if (distance < 4) { // This is where the LED On/Off happens

If the youtube video is anything to go by I assume that "4" equals 4cm which means that for my purpose I would need it to be as follows?

if (distance < 400 ) { // This is where the LED On/Off happens

Correct?

HendrikB7 (author)2017-04-30

Excellent project that immediately make me think of using it for motorcycle safety of the motorcyclist as one can indicate backwards towards an approaching vehicle that it is too close!!!

Nothing to do with the project only the sensor is that I would have liked to be able to detect up to at least 10 meters.

sutto007 made it! (author)2017-04-27

very simple but very useful little project, let the fun begin.

moronicfag (author)2017-04-23

my students think this project is very useful to many and can find this very useful

EricW229 made it! (author)2017-04-19

Good instructions, excellent introduction to sonar, worked without a hitch. Only tweak I made was to change the trigger distance to 10cm rather than 4cm - for my sensor at least, objects closer than 5cm were not detected reliably. This is a physical issue with the sonar unit, not a problem with the code.

TrondC made it! (author)2017-03-22

I didn't bother with the LED's and used a 16x2 display to display distance instead :)

mikey_lambert (author)TrondC2017-04-15

What are the pots for?

crazytechkid (author)2017-03-15

when i go into the serial monitor it just says out of range over and over agin. can someone help?

DavidB552 (author)crazytechkid2017-04-11

I suspect your wiring is dodge and so its not getting any singal check your wireing first

Ke ShavG (author)2017-03-06

i have 2 aduinos , mega and uno . i have an ultrasonic sensor . i want to record distance from the ultrsonic and send it via rf 433hz module to the recieve which will display the data on a 16x2 lcd . can some do the codes. i am new to programmig , and i need to submit my project . please

Ke ShavG (author)Ke ShavG2017-03-14

anyone that can help??

DavidB552 (author)Ke ShavG2017-04-11

also trying to do that il let you know if I have a break though if you let me know ?

sachinv12 made it! (author)2017-03-01

hey thanx man, i tweaked it and made a working parking indicator with leds switching off with length and increasing frequency of speaker with decrease in distance.

DuB805 made it! (author)2017-02-25

Worked great! Thank you very much for the information. It will be used for me to continue learning about arduino!! I plan on combining it with many other projects.

jeanlouisquero (author)2017-02-25

Ok thanks it works in a scketch alone but when i add engines nothing happens

I had to make a mistake but I'm starting and I'm not sure how to write the program.

I replaced the led by the engines?


Can you help me thanks

Cordially


#include <Stepper.h>

#include <Ultrasonic.h>

//#include <Servo.h>
#define trigPin 13
#define echoPin 12

//moteur droit
int L298N_IN1=9;
int L298N_IN2=8;
int L298N_ENA =2;
//moteur gauche
int L298N_IN3=7;
int L298N_IN4=6;
int L298N_ENB =3;


void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);


pinMode(L298N_IN1, OUTPUT);
pinMode(L298N_IN2, OUTPUT);
pinMode(L298N_IN3, OUTPUT);
pinMode(L298N_IN4, OUTPUT);
pinMode(L298N_ENA, OUTPUT);
pinMode(L298N_ENB, 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(L298N_IN1,HIGH); // When the Red condition is met, the Green LED should turn off
digitalWrite(L298N_IN2,LOW);
digitalWrite(L298N_IN3,HIGH);
digitalWrite(L298N_IN4,LOW);
}
else {
digitalWrite(L298N_IN1,LOW);
digitalWrite(L298N_IN2,HIGH);
digitalWrite(L298N_IN3,LOW);
digitalWrite(L298N_IN4,HIGH);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);

digitalWrite(L298N_ENA, HIGH);
digitalWrite(L298N_ENB, HIGH);


startCar();
delay(1000);
stopCar();
delay(1000);
leftTurn();
delay(1000);
rightTurn();
delay(1000);

}

void startCar()
{

digitalWrite(L298N_IN1, HIGH);
digitalWrite(L298N_IN2, LOW);
digitalWrite(L298N_IN3, HIGH);
digitalWrite(L298N_IN4, LOW);
}
void stopCar()
{
digitalWrite(L298N_IN1, LOW);
digitalWrite(L298N_IN2, LOW);
digitalWrite(L298N_IN3, LOW);
digitalWrite(L298N_IN4, LOW);

}
void leftTurn()
{
digitalWrite(L298N_IN1, LOW);
digitalWrite(L298N_IN2, HIGH);
digitalWrite(L298N_IN3, HIGH);
digitalWrite(L298N_IN4, LOW);

}
void rightTurn(){


digitalWrite(L298N_IN1,HIGH );
digitalWrite(L298N_IN2, LOW);
digitalWrite(L298N_IN3,LOW );
digitalWrite(L298N_IN4, HIGH);
}

JeffD158 made it! (author)2017-02-17

Works great. I just bought a 5 pack of these from Amazon for a song. I followed your instructions and it works great. One question though, you changed a few things in the code (specifically the delayMicroseconds(1000)) and added much lower delay values elsewhere. Why these changes? What did you fix with these changes?

varsha34ts (author)2017-01-22

every time the output is displayed as out of range and if i modify
the code to measure distance its displayed as 0cm..whats the reason?

even
with the other code including the example code for ping sensors the
distanced is displayed as 0cm ...but with other arduino board the code
is working fine and the correct distance is being measured which implies
my sensor working fine...then wat may be the problem?

ELJIE (author)2017-01-17

if i'll use arduino mega 2560, do the codes be the same? Please help. thank you.

AbdullahZ13 (author)ELJIE2017-01-21

Yes it will be same.

ruchi1246 (author)2017-01-18

How could I get the my project specific details? How does paid membership work?

gbushta (author)2017-01-18

Very nice tutorial. I like that I didn't have to download and install a new library into the Arduino libraries.
I made this with only one LED and resistor. I set it up to make the LED brighter the closer the object was to the sensor. LED on pin 6 (PWM type pin) on Arduino.
if (distance > 0 && distance < 200) { //if distance is between 0 and 200
analogWrite(led, 255/distance); //use PWM to light the LED
}else{
analogWrite(led, 0); // if the distance is greater than 200 turn off the LED
}

Fathima ashif ikbal (author)2016-12-16

It shows pulseln not defined what should i do

I ran into the same trouble. I changed it to read:

duration = pulseIn(echoPin, HIGH);

pulseIn, like pulse in and not LN.

hpdoeswurk (author)2016-12-29

how can you add more than one sensor, say like 5? Is there a limit to how many sensors you can have running at the same time, like there is with servos?

RicardoH29 (author)hpdoeswurk2017-01-17

Using the general idea in his code, yes, you can add more sensors. If you can have them share the same pins, then there virtually no limitation (unless you start overwhelming your power supply). Otherwise, if you need them fully independent from one another, then you are limited by the number of digital I/O pins you have available.

Note that servos require a special kind of digital I/O pins, i.e. PWM (Pulse Width Modulation) capable pins. The HC-SR04 does not.

EltonO made it! (author)2016-12-27

Just received the HC-SR04 and thanks to you I tested it :D

Physics Pro (author)2016-12-21

could you tell me from where you got the hc-sro4 part in fritzing? I am getting tired searching for it

SulimanD (author)2016-12-16

can you help me ?

i want code arduino nano with buzzer conection it can you ?

Lbotero made it! (author)2016-11-29

Great ! Finally I got the Ultrasonic Sensor to work. Thank you for the tutorial.

SulimanD (author)Lbotero2016-12-16

possible give me code arduino nano conection with led :)

Esra ChristianS (author)2016-12-14

Thank u for this tutorial. Bu t i wanna ask u about the formula. Why the formula to find the distance is "(duration/2/29.1)"?

LeiserC (author)2016-11-25

Thankyou so much for this great tuitorial. It worked great but the Echo and Trig wires have to be switched, as AbhijitK24 said. I connected it up to my device and put the arduino ona portbale battery making it so I can move it around as needed, such as on an rc car.

AbhijitK24 (author)2016-11-24

Need a small edit. The code comment says

Echo to Arduino pin 13

Trig to Arduino pin 12

but the code itself uses (and this matches the Fritzing sketch)

#define trigPin 13

#define echoPin 12

FixieG made it! (author)2016-11-23

Very Nice Tutorial!!

Works fine!!

GrandadBob made it! (author)2016-11-15

Works very well even using my inexpensive NHduino Uno from china, when my cheep display arrives (For Arduino UNO/MEGA/Nano TFT Color Display Module Breakout SPI ST7735S 1.8 inch
) £2.80 I'm going to try and have the display update with actual live distance :) Thanks for the cool info.

( 381468326011 )

jomahera (author)2016-08-29

Works great!

asri rahman (author)jomahera2016-11-11

ok

tusharsonawane (author)2016-05-05

Can you please link us to that thing on which you have kept the arduino and the breadboard ?

About This Instructable

1,112,842views

362favorites

License:

More by jsvester:Simple Arduino and HC-SR04 Example
Add instructable to: