Getting Started with the HC-SR04 Ultrasonic sensor

A basic introduction to the low cost and accurate HC-SR04!

Aug 5, 2017

521137 views

110 respects

Components and supplies

1

Breadboard (generic)

1

Arduino UNO

1

Ultrasonic Sensor - HC-SR04

1

Jumper wires (generic)

Apps and platforms

1

Arduino IDE

Project description

Code

Downloadable files

HC-SR04 Diagram

HC-SR04 Diagram

Comments

Only logged in users can leave comments

getcom11

a month ago

Hi, I just started playing <a href="https://getcompressedgames.com/soulcalibur-vi-highly-compressed/">SoulCalibur VI</a>. I love the combat mechanics and the character roster so far! However, I’m curious—what are the best strategies for mastering the Reversal Edge system? Any tips on timing or counters would be super helpful!"

Aswinth

8 months ago

Nice, I recently made a tutorial on how ultrasonic sensor works and how to use them with Arduino with some cool infographics. If you wish to read here is the link https://circuitdigest.com/microcontroller-projects/interface-arduino-with-ultrasonic-sensor - have used the same library

marwan1515

8 months ago

hello can i contact with u on WhatsApp or telegram plzzzzz i need help with my gradation project ((There is a financial return for you)) if u accept to help me waiting for ur response thank you

saburhipps920

9 months ago

Help me

e11t9in20

a year ago

The code worked Thank you. I just encountered one issue and that is that the serial output looked like this distance: 0 Distance : 122 Distance: 0 Distance: 121 etc etc. I was wondering if anyone knew why and how to fix it?

rubenhamers2007

a year ago

Hey, lil question does the sensor read in cm and ifso how accurate. Ty

e11t9in20

a year ago

Yes the distance is in cm and should be accurate +- 0.5 cm however if the object is whool the sound might not bounce and their are a lot of factors which stop the sensor from sensing an object but when it senses it it is quite accurate.

e11t9in20

a year ago

Yes the distance is in cm and should be accurate +- 0.5 cm however if the object is whool the sound might not bounce and their are a lot of factors which stop the sensor from sensing an object but when it senses it it is quite accurate.

gigatesseract

a year ago

Hey this is a really nice guide. I am starting with arduino, I have a super noob question. According to the documentation of pulseIn: ``` Measures the length (in microseconds) of a pulse on the pin; state is HIGH or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds to 3 minutes in length, but must be called at least a few dozen microseconds before the start of the pulse. ``` So, from the code, ``` digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); ``` The echoPin must be set to HIGH a few dozen microseconds `after` pulseIn is called. Therefore, we kind of assume that by the time the instruction pulseIn is executed, the pin is still in LOW state. This will be possible only when the sound returns to the echoPin `after` the pulseIn is called. Therefore, the sound must be in transit for atleast 10 microseconds. Therefore, the distance between the sensor and the object should be atleast the distance that sound travels in 5 microseconds. Therefore, the minimum distance that can be measured would be: 340 m / s * 5 * 10^-6 s = 1700 * 10^-6m = 0.0017m = 1.7mm. We also cannot have a higher delay because by the time delay completes, the echoPin MUST BE OFF. Is my interpretation right? The code restricts the minimum and maximum distance that can be measured?

rachna52

a year ago

For more detailed guide checkout this blog: https://playwithcircuit.com/ultrasonic-sensor-hc-sr04-interfacing-with-arduino/

Anonymous user

2 years ago

The sample file does an excellent job, thank you very much! I do have a question, however: while checking serial monitors and ports (especially noticeable on the latter), I'll occasionally see random spikes in distance that couldn't be possible, such as increases and decreases of thousands of centimeters over the course of a few milliseconds. Does anyone know what causes this? My first assumption was electrical noise, but I'm still a beginner with this and don't have an iron-cast grasp on all things electrical yet.

panagorko

2 years ago

If the ultrasonic wave didn't return loop in the sensor times out so Arduino code won't freeze waiting infinitely in pulseIn function. After ~14000µs without signal sensor times out and I think this is the case. If you want to get more complex guide about hcsr04 check this: https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478

gandalf12

2 years ago

It is possible that it could be the 2 microsecond set to low at the beginning of the loop too.

Anonymous user

2 years ago

Hi, I am using ultrasonic sensor with 15 VDC. Is it compatible with Arduino UNO? What kind of changes I have to made with the circuit?

Anonymous user

2 years ago

the 5v version sells for about $1 online.

Anonymous user

2 years ago

it is best project but i got the output as distance 0.00 and it is continuously scrolling

Anonymous user

2 years ago

bro this is so cool

spudnut1

2 years ago

Great example and very clear... Used it to 'seed' my corona virus hand washing device.

IoT_hobbyist

2 years ago

For corona virus hand washing touchless device, you need to use a servo motor, see how ultrasonic sensor trigger servo motor: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor-servo-motor

Anonymous user

2 years ago

First, the trigger and echo pins on your last diagram are swapped relative to the device I have. It might be worth calling that out? Second, I think I have a bad device. 95% of the time, I get a result of 0.60. Occasionally I get a 0.62 or a 0.57. Even more rarely, 0.55 or 0.47. (On the off chance that it was the swapped pins, I tried reversing them, but as expected, the pulseIn stops triggering, so I know that my pinouts are correct. The type of surface I put in front of the sensor doesn't matter. My hand, plastic, wood, etc.

panagorko

2 years ago

It's problem with sensor accuracy. But it can be easily fixed check this tutorial: https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478 I think this is the case.

ryker1234

2 years ago

where do you see the readings

Syronide

2 years ago

On the serial monitor. To open the serial monitor just click on the button in the top right of your sketch.

Anonymous user

2 years ago

'trigPin' was not declared in this scope how do i fix?

Anonymous user

2 years ago

hi, the code work perfectly without error. but the longest distance I could get is around 5.xx. Any suggestion? thanks. eg. 9:42:24.521 -> Distance: 4.80 09:42:24.614 -> Distance: 4.70 09:42:24.707 -> Distance: 4.15 09:42:24.801 -> Distance: 4.37 09:42:24.941 -> Distance: 5.76 09:42:25.035 -> Distance: 5.76 09:42:25.127 -> Distance: 5.68 09:42:25.223 -> Distance: 5.78 09:42:25.316 -> Distance: 5.68 09:42:25.409 -> Distance: 5.76 09:42:25.505 -> Distance: 5.76 09:42:25.645 -> Distance: 5.76

Unsigned_Arduino

2 years ago

Great job on the tutorial! Anyway, can you help me on the distance variable? What type of measurements is the distance variable? Is it centimeter?

Isaac100

2 years ago

Centimeters

Anonymous user

2 years ago

Good day! how many HC-SR04 can be used in Arduino 2560?Thanks for your help

ryker1234

2 years ago

how does it work and how do you see how far things are?

Anonymous user

2 years ago

By sending ultra waves.

Anonymous user

2 years ago

Thanks for this helpful example. I noticed that the main loop was blocking which stops the Arduino from executing other tasks at the same time so I had a look into this. If you're interested, you can see what I found here... http://theonlineshed.com/arduino-multi-tasking The short story is that I moved your code out of the main loop and into PWM and interrupts so the main loop is now free to do other cool stuff. Thanks all of you in the Arduino community for helpful posts like this and the other ones linked in my post.

gaganghu

2 years ago

Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno" \\cci1OJQr.ltrans0.ltrans.o:(.rodata+0x6): undefined reference to `Print::write(unsigned char const*, unsigned int)' c:/users/umesh/downloads/arduino/hardware/tools/avr/bin/../lib/gcc/avr/7.3.0/../../../../avr/lib/avr5/crtatmega328p.o:(.init9+0x0): undefined reference to `main' collect2.exe: error: ld returned 1 exit status exit status 1 Error compiling for board Arduino/Genuino Uno. This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

Anonymous user

2 years ago

Nice! The explanation is very helpful! I'm also using this type of ultrasonic sensor for my project. Just wondering if there is an intensity threshold for this ultrasonic sensor to consider a return signal as a valid echo? And are we allow to manipulate this threshold using Arduino?

Anonymous user

2 years ago

My first try is a minimalist setup of a pulse generator (at 1Hz, 1% duty cycle), an SRF04 and a basic dual-trace oscilloscope (sweep triggered by the output of the pulse generator, time base set to 5mS/div) . I made a video and the link is below. I could show the input pulse to the SRF04 or the SRF04 output, but the 'scope was always triggered by the output of the 1Hz pulse generator. The wall behind me is just short of 4 Ft from the SRF04, so the default output pulse would be about 16 mS. That was the case for some of the pulses. Some were longer than the screen could show, and some were very short. Placing a box in the beam didn't change much. The short SRF04 output pulses 1. Didn't start until the trigger pulse returned low (not expected, but still workable). 2. the very short output pulses were about the length expected for the box's distance, but those short pulses also showed intermittently when only the wall was in the path (4Ft away). The video can be seen on FaceBook at: https://bit.ly/2rapp1e Note as I'm editing these comments, I suspect I'm mixing up milliseconds and microseconds in my pulse width timing estimates. Stay tuned.

Anonymous user

2 years ago

This project is very clear to understand. Thanks!

Anonymous user

2 years ago

Is it possible to put the output on a qapass 1602a so that you can have a portable distance measurer? That would bring this to the next level.

Anonymous user

2 years ago

Is it possible to place two ultrasonic sensors next to each other? In this case does it matter wich way around you place them? We have two sensors next to each other, but they give random distances, who not match with what they need to see. Also the measurement of both are very different.

Anonymous user

2 years ago

Thanks for your fairly detailed explanation with a bit of Physics =) Other articles simply just copy and pasted some code somewhere. You also might have done that, but thanks for the extra effort in explaining!

Anonymous user

2 years ago

how it works

aldo24

2 years ago

What measurement is the "distance" variable in?

Isaac100

2 years ago

Centimeters

jacobperdelius

2 years ago

Hi, in a school project I and a friend are building a self-driving car in which it will have three sensors at the front. But I won't get a reading from one of the sensors. Can anyone help me? Here's the code and to differ the two sensors I one of the texts in Swedish const unsigned int TRIG_PIN1=13; const unsigned int ECHO_PIN1=12; const unsigned int TRIG_PIN2=11; const unsigned int ECHO_PIN2=10; const unsigned int BAUD_RATE=9600; void setup() { pinMode(TRIG_PIN1, OUTPUT); pinMode(ECHO_PIN1, INPUT); pinMode(TRIG_PIN2, OUTPUT); pinMode(ECHO_PIN2, INPUT); Serial.begin(BAUD_RATE); } void loop() { digitalWrite(TRIG_PIN1, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN1, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN1, LOW); digitalWrite(TRIG_PIN2, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN2, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN2, LOW); const unsigned long duration1= pulseIn(ECHO_PIN1, HIGH); int distance1= duration1/29/2; if(duration1==0){ Serial.println("Warning: no pulse from sensor"); } else{ Serial.print("distance to nearest object:"); Serial.println(distance1); Serial.println(" cm"); } delay(100); const unsigned long duration2= pulseIn(ECHO_PIN2, HIGH); int distance2= duration2/29/2; if(duration2==0){ Serial.println("Varning: ingen puls från sensor"); } else{ Serial.print("distans till närmsta objekt"); Serial.println(distance2); Serial.println(" cm"); } delay(100); }

Anonymous user

2 years ago

Nice tutorial!

bessn4977

2 years ago

gooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood

Anonymous user

2 years ago

Thanks for the clear tutorial! I'm strughlingvto understand why you use HIGH as argument for pulseIn? Won't that return the pulse duration of 10 microseconds? Should't it be LOW to meadure the pulse travel time?

Anonymous user

2 years ago

Hi, can you you point me in the right direction for the following? If I can just figure this part out I think I can take it from there. -If distance is below a set amount, send a mouse click to a specific place on screen and then check distance again and repeat until set distance range has been met. Basically, an if/then action based on the distance check. Thank you for the tutorial!

Anonymous user

2 years ago

such a wonderful project, i ran into problems doing my project, i want an arduino that may read under water with successful imaging underwater

Anonymous user

2 years ago

I don't quite understand in this project, does it work as a transmitter or a receiver? Or emtra both by alternating various tx\ x states? Thank you very much.

Anonymous user

2 years ago

'trigPin' was not declared in this scope how do i fix?

Anonymous user

2 years ago

hi, the code work perfectly without error. but the longest distance I could get is around 5.xx. Any suggestion? thanks. eg. 9:42:24.521 -> Distance: 4.80 09:42:24.614 -> Distance: 4.70 09:42:24.707 -> Distance: 4.15 09:42:24.801 -> Distance: 4.37 09:42:24.941 -> Distance: 5.76 09:42:25.035 -> Distance: 5.76 09:42:25.127 -> Distance: 5.68 09:42:25.223 -> Distance: 5.78 09:42:25.316 -> Distance: 5.68 09:42:25.409 -> Distance: 5.76 09:42:25.505 -> Distance: 5.76 09:42:25.645 -> Distance: 5.76

Anonymous user

3 years ago

Hi, can you you point me in the right direction for the following? If I can just figure this part out I think I can take it from there. -If distance is below a set amount, send a mouse click to a specific place on screen and then check distance again and repeat until set distance range has been met. Basically, an if/then action based on the distance check. Thank you for the tutorial!

Anonymous user

3 years ago

Good day! how many HC-SR04 can be used in Arduino 2560?Thanks for your help

bessn4977

4 years ago

gooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood

Anonymous user

4 years ago

Nice! The explanation is very helpful! I'm also using this type of ultrasonic sensor for my project. Just wondering if there is an intensity threshold for this ultrasonic sensor to consider a return signal as a valid echo? And are we allow to manipulate this threshold using Arduino?

Anonymous user

4 years ago

Is it possible to place two ultrasonic sensors next to each other? In this case does it matter wich way around you place them? We have two sensors next to each other, but they give random distances, who not match with what they need to see. Also the measurement of both are very different.

mikethepariah

4 years ago

Thanks for your fairly detailed explanation with a bit of Physics =) Other articles simply just copy and pasted some code somewhere. You also might have done that, but thanks for the extra effort in explaining!

Anonymous user

4 years ago

how it works

Anonymous user

4 years ago

it is best project but i got the output as distance 0.00 and it is continuously scrolling

gandalf12

4 years ago

Is it possible to put the output on a qapass 1602a so that you can have a portable distance measurer? That would bring this to the next level.

jacobperdelius

4 years ago

Hi, in a school project I and a friend are building a self-driving car in which it will have three sensors at the front. But I won't get a reading from one of the sensors. Can anyone help me? Here's the code and to differ the two sensors I one of the texts in Swedish const unsigned int TRIG_PIN1=13; const unsigned int ECHO_PIN1=12; const unsigned int TRIG_PIN2=11; const unsigned int ECHO_PIN2=10; const unsigned int BAUD_RATE=9600; void setup() { pinMode(TRIG_PIN1, OUTPUT); pinMode(ECHO_PIN1, INPUT); pinMode(TRIG_PIN2, OUTPUT); pinMode(ECHO_PIN2, INPUT); Serial.begin(BAUD_RATE); } void loop() { digitalWrite(TRIG_PIN1, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN1, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN1, LOW); digitalWrite(TRIG_PIN2, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN2, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN2, LOW); const unsigned long duration1= pulseIn(ECHO_PIN1, HIGH); int distance1= duration1/29/2; if(duration1==0){ Serial.println("Warning: no pulse from sensor"); } else{ Serial.print("distance to nearest object:"); Serial.println(distance1); Serial.println(" cm"); } delay(100); const unsigned long duration2= pulseIn(ECHO_PIN2, HIGH); int distance2= duration2/29/2; if(duration2==0){ Serial.println("Varning: ingen puls från sensor"); } else{ Serial.print("distans till närmsta objekt"); Serial.println(distance2); Serial.println(" cm"); } delay(100); }

Anonymous user

4 years ago

Hi, I am using ultrasonic sensor with 15 VDC. Is it compatible with Arduino UNO? What kind of changes I have to made with the circuit?

Anonymous user

2 years ago

the 5v version sells for about $1 online.

Anonymous user

4 years ago

Thanks for this helpful example. I noticed that the main loop was blocking which stops the Arduino from executing other tasks at the same time so I had a look into this. If you're interested, you can see what I found here... http://theonlineshed.com/arduino-multi-tasking The short story is that I moved your code out of the main loop and into PWM and interrupts so the main loop is now free to do other cool stuff. Thanks all of you in the Arduino community for helpful posts like this and the other ones linked in my post.

Anonymous user

4 years ago

First, the trigger and echo pins on your last diagram are swapped relative to the device I have. It might be worth calling that out? Second, I think I have a bad device. 95% of the time, I get a result of 0.60. Occasionally I get a 0.62 or a 0.57. Even more rarely, 0.55 or 0.47. (On the off chance that it was the swapped pins, I tried reversing them, but as expected, the pulseIn stops triggering, so I know that my pinouts are correct. The type of surface I put in front of the sensor doesn't matter. My hand, plastic, wood, etc.

panagorko

2 years ago

It's problem with sensor accuracy. But it can be easily fixed check this tutorial: https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478 I think this is the case.

YoGamer

4 years ago

Nice tutorial!

spudnut1

5 years ago

Great example and very clear... Used it to 'seed' my corona virus hand washing device.

IoT_hobbyist

2 years ago

For corona virus hand washing touchless device, you need to use a servo motor, see how ultrasonic sensor trigger servo motor: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor-servo-motor

Anonymous user

5 years ago

The sample file does an excellent job, thank you very much! I do have a question, however: while checking serial monitors and ports (especially noticeable on the latter), I'll occasionally see random spikes in distance that couldn't be possible, such as increases and decreases of thousands of centimeters over the course of a few milliseconds. Does anyone know what causes this? My first assumption was electrical noise, but I'm still a beginner with this and don't have an iron-cast grasp on all things electrical yet.

panagorko

2 years ago

If the ultrasonic wave didn't return loop in the sensor times out so Arduino code won't freeze waiting infinitely in pulseIn function. After ~14000µs without signal sensor times out and I think this is the case. If you want to get more complex guide about hcsr04 check this: https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478

Anonymous user

2 years ago

It is possible that it could be the 2 microsecond set to low at the beginning of the loop too.

gaganghu

5 years ago

Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno" \\cci1OJQr.ltrans0.ltrans.o:(.rodata+0x6): undefined reference to `Print::write(unsigned char const*, unsigned int)' c:/users/umesh/downloads/arduino/hardware/tools/avr/bin/../lib/gcc/avr/7.3.0/../../../../avr/lib/avr5/crtatmega328p.o:(.init9+0x0): undefined reference to `main' collect2.exe: error: ld returned 1 exit status exit status 1 Error compiling for board Arduino/Genuino Uno. This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

Anonymous user

5 years ago

My first try is a minimalist setup of a pulse generator (at 1Hz, 1% duty cycle), an SRF04 and a basic dual-trace oscilloscope (sweep triggered by the output of the pulse generator, time base set to 5mS/div) . I made a video and the link is below. I could show the input pulse to the SRF04 or the SRF04 output, but the 'scope was always triggered by the output of the 1Hz pulse generator. The wall behind me is just short of 4 Ft from the SRF04, so the default output pulse would be about 16 mS. That was the case for some of the pulses. Some were longer than the screen could show, and some were very short. Placing a box in the beam didn't change much. The short SRF04 output pulses 1. Didn't start until the trigger pulse returned low (not expected, but still workable). 2. the very short output pulses were about the length expected for the box's distance, but those short pulses also showed intermittently when only the wall was in the path (4Ft away). The video can be seen on FaceBook at: https://bit.ly/2rapp1e Note as I'm editing these comments, I suspect I'm mixing up milliseconds and microseconds in my pulse width timing estimates. Stay tuned.

STEMCafe

5 years ago

This project is very clear to understand. Thanks!

Anonymous user

5 years ago

bro this is so cool

Willyaminedada

5 years ago

Thanks for the clear tutorial! I'm strughlingvto understand why you use HIGH as argument for pulseIn? Won't that return the pulse duration of 10 microseconds? Should't it be LOW to meadure the pulse travel time?

Isaac100

2 months ago

Sorry, I worded it incorrectly and have updated it. The trig pin goes high when the sound waves are sent and goes low when they return.

ryker1234

5 years ago

where do you see the readings

Anonymous user

2 years ago

On the serial monitor. To open the serial monitor just click on the button in the top right of your sketch.

ryker1234

5 years ago

how does it work and how do you see how far things are?

Anonymous user

2 years ago

By sending ultra waves.

Anonymous user

6 years ago

such a wonderful project, i ran into problems doing my project, i want an arduino that may read under water with successful imaging underwater

aldo24

6 years ago

What measurement is the "distance" variable in?

Anonymous user

2 years ago

This is a different group, but it explains SRF04 timings/distances very well: https://randomnerdtutorials.com/complete-guide-for-ultrasonic-sensor-hc-sr04/

Isaac100

2 years ago

Centimeters

Unsigned_Arduino

6 years ago

Great job on the tutorial! Anyway, can you help me on the distance variable? What type of measurements is the distance variable? Is it centimeter?

Isaac100

2 years ago

Centimeters