Simple Arduino and HC-SR04 Example

1.4M428347

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

255 Comments

Superb Instructable for a beginner like me. The distance measurement bit works perfectly. The LED 1 goes on and off correctly. LED2 remains unaffected though. I have made all connections as displayed, code is copied too. The only change is, instead of 560, I am using 1K resistors (worked with 220 as well). How could I troubleshoot this to figure out the issue? Any pointers
Hai Sir, As we know ultrasonic sensor range is aout 2cm to 400cm.
But I want to measure the distance which is greater than 400cm.
Is there any possible way for increasing the range of HC-SR04 Circuit or Is there any sensor which measuring range is greater than 400cm.
I'm not getting the stable values around the range of 400cm with HC05 Sensor.
Thanks in Advance.
http://uitechies.co.in/BBBcircuits/product.php?product=ultrasonic-range-finder-module-sensor-distance-measuring-transducer
I have interfaced Ultrasonic with Arduino. Now, I want to ON and OFF the LED when the distance is less than 15cm. I have written the code as
if(distance < 15) {
digitalWrite(led,HIGH); }
else {
digitalWrite(led,LOW); }
But the LED was not HIGH when the distance is less than 15
I have no idea why the LED was not HIGH, please help me.
Thanks in Advance.
I have purchased the ultrasonic sensor
http://uitechies.co.in/BBBcircuits/product.php?product=ultrasonic-range-finder-module-sensor-distance-measuring-transducer
Does anyone have this project (excellent BTW) that uses a speaker and tones as the target gets closer? Similar to how a car object sensor works? Thanks

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

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

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!

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

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

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.

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.

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

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.

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.

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

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.

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

Great for testing device thanks!

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

More Comments