Simple Arduino and HC-SR04 Example

1,227,493

378

250

Intro: 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

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

47 People Made This Project!

Recommendations

  • Halloween Contest 2018

    Halloween Contest 2018
  • Optics Contest

    Optics Contest
  • Plastics Contest

    Plastics Contest

250 Discussions

0
None
MarkR387

Tip 5 months ago on Step 3

I wanted to use this type of thing for an alarm. So what I did was to have it that it would check the distance that it was reading to the wall (or other objects in the room) after 5 seconds then use that number as the distance number (variable). Then anything shorter than that distance an alarm would go off. But what was nice about this solution is that when it is turned on, you could put it anywhere and it would automatically calibrate! Great work on this tutoria

0
None
RobM230

7 months ago

By the way, I substituted an HC-SR05 (longer range, I believe) for the SR04.

0
None
RobM230

7 months ago on Introduction

Awesome. I had been struggling trying to build a working garage parking assist and this was just the sketch I needed. I did add a yellow LED as an intermediate alert. The proto works great. Transferring it now to an enclosure. I'll post a pic when completed. Anyway, thanks for posting the tutorial!

0
None
MelisaY

Question 9 months ago on Step 2

I have this completed and had so much fun but my next step is how can I have it so once the led changes color the interface loads a .html file?

Thanks

0
None
AlphaOmega1

10 months ago

Nice project, well done. Endless fun with ultrasonic rangers, and so cheap!

May I add the following? ...

If you are expecting to always range closer objects than the maximum (4M?), then to save time in your loop, you can change the value of timeOut as follows...

timeOut is not used above

duration = pulseIn(echoPin, HIGH [, timeOut]);

By using a timeout, your program spends less time waiting for a reflection that isn't coming back or is too far away to be of use to you.

timeOut is in microseconds

We can set the timeout to coincide with a required max distance quite easily. Since sound travels at about 0.034 cm per microsecond and say we want to measure a maximum of 50 cm. Then...

Remember we measure the time to reach the object and then the return journey, so here we are talking about 100cm (1M) round trip for this example

1cm = 29.4mS so our timeOut value becomes 29.4 x 50 x 2 = 2940

If the ping takes longer than timeOut then zero (0) is returned in "duration"! Nice!

so, in the above example, something like

if ( duration >= 2940 || duration <= 0){

Serial.println("Out of range");
}

becomes

if (duration == 0){

Serial.println("Out of range");
}

The pulseIn() function requires interrupts to be enabled, so "noInterrupts()" can not be used if using pulseIn()

see also pulseInLong()

0
None
NikonUser

1 year ago

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.

3 replies
0
None
graham641NikonUser

Reply 11 months ago

I assume that you are using the HC-SR04 sensor. It is an indoor type sensor with only a screen to protect it. Likely it will have a short life. You might consider the enclosed sensors that can brave the elements. Check Mouser or Digi-key for an enclosed sensor. The problem with enclosed sensors is that they do require a higher drive voltage and are less sensitive. Clever application.

0
None
smj135NikonUser

Reply 11 months ago

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

0
None
NikonUsersmj135

Reply 11 months ago

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.

0
None
mikey_lambert

1 year ago

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.

2 replies
0
None
ThomasW165mikey_lambert

Reply 1 year ago

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

0
None
NikonUsermikey_lambert

Reply 1 year ago

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.

0
None
happyman1111

1 year ago

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

SIFriendlyFire.png
0
None
misterxp

1 year ago

Great for testing device thanks!

0
None
NeepaB

1 year ago

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

0
None
Strato_caster

1 year ago

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.

0
None
HendrikB7

1 year ago

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?

0
None
HendrikB7

1 year ago

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.

0
None
moronicfag

1 year ago

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

0
None
crazytechkid

1 year ago

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