What does a parking sensor, burglar alarm and submarine have in common? That’s right, they use distance sensing. In this tutorial, I will be showing you how to use an Arduino along with an HCSR04 or equivalent ultrasonic/sonar sensor for measuring distances. Let’s get started!
What is it and how does it work?
An HC SR04 is a SONAR (SOund NAvigation and Ranging, click here to know more) sensor which uses ultrasonic sound waves to measure sound. It does this by sending out a pulse of sound from the transimitter, which then gets reflected back from a target and reaches the receiver. The total time this takes is recorded by the Arduino and the distance is calculated from it. You might have realized, that this is just like a bat or a submarine!
The cost and interface provided by the sensor is what makes it popular among and differentiates it from the other sensors. A ten microsecond HIGH pulse is sent to the trigger pin (labeled “trigg”) and then a timer is started which waits until a HIGH is received. The distance is then calculated from this value.
Step 1: Gathering the parts
In order to complete this project, you will need the following parts-
- Arduino UNO or equivalent (along with programming cable)
- HCSR04 sensor
- Connecting Wires
- Breadboard (optional)
- LED (optional)
Step 2: Connecting everything up
In this step, I will show you how to connect all the components in the circuit. Start by connecting the VCC and GND on the sensor to 5v and GND on the Arduino. Then connect the trigger and echo pin of the sensor to the Arduino. I have used pins 5 and 4 respectively but you can use any of the digital pins.
Finally, connect the LED (optional) to pin 13. We will be using this in step 4. You’re done!
Step 3: Coding and Uploading
Now, it’s time for my favourite bit, writing the code and uploading. If you are not familiar with Arduino coding, then click here to know more.
Start by defining the trigger and echo pin as shown below-
Next, in the setup, set the pin modes of the pins and start the Serial monitor. If you do not know what the Serial monitor, or want to understand how to use it, click here.
Finally, in the loop, create a 10 microsecond pulse on the trigger and print the distance on the serial monitor like shown below-
Compile and upload this to your Arduino, and you’re done. Now you too have a working distance sensor.
Step 4: Playing around a bit
After you have got the circuit working, try to find out the minimum and maximum distance the sensor can measure.
Try to make a proximity sensor using the LED on pin 13. It should light up when something is lesser than or equal to a specific distance away from the sensor and shuts of when it moves away.
You can even try a slightly more ambitious project like a parking sensor or an obstacle avoiding car. Its all up to you!
- Wikipedia article on sonar
- Getting started with Arduino
- Serial communication with Arduino