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 the sensor and the obstacle.

Example of distance calculation

Speed of sound:
v = 340 m/s
Time = distance / speed
t = d / v
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 to 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).


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.

Leave a Reply

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