Arduino UNO – Ultrasonic Sensor HC-SR04

In this tutorial I am going to show you how to use an Ultrasonic Sensor (HC-SR04) with Arduino UNO. You can use any Arduino Board.
HC-SR04 emits an ultrasound (high frequency), which spreads through the air and if there is an obstacle on its path it will come back (reflection) to the HC-SR04. Through the travel time and the speed of the sound (340 m/s), you can compute the distance between sensor and obstacle.

Example of distance calculation

Speed of sound:
v = 340 m/s
Time = distance / speed
t = d / v
Distance:
d = t * 340 / 2
(divide by 2 because total time is round trip sound).

Parts Required

  • Arduino Mega 2560;
  • Breadboard (optional);
  • 1x HC-SR04;
  • Jumper wires.

Building the Circuit and Schematic

You need to connect the power to the sensor (red and black lines) and you need connect trigPin (Output) to Arduino pin 11 and echoPin(Input) to Arduino pin 12. You can use other Arduino pins, but you should change the pins at the beginning of the code (#define pinName pinNumber).

Code

If you compile the code and send it to Arduino without errors, you will see on your monitor that the distance is measured and displayed every 500 ms. Do not forget that the obstacle cannot be too near or too far or the distance will be -1.

Any questions send us a message or leave a comment.

Please follow and like us:
João Louro

Author: João Louro

Electrical Engineer with special interest in Embedded Systems, Real Time Operating Systems and Audio. With a degree in Electrical and Computer Engineering in the field of Electronics and Computers and currently studying Master's degree in Electrical Engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *