In this tutorial, I will be going through the steps on how to set up an Arduino distance sensor using the HC-SR04 ultrasonic sensor.

This project aims to help you design a simple system that can measure the proximity of an object from a target. The sensor to be used is the Ultrasonic sensor. The Ultrasonic sensor works with the principle of reflected sound waves and can be used to measure distance, detect the presence of an object and determine the level of water.




The Ultrasonic Sensor works on the principle of reflected sound waves and are used to measure the proximity of a body or object to another.  One sensor can detect others operating nearby. The Sensor head emits an ultrasonic wave and receives the wave reflected back from the object and we can use this feature to measure the distance by measuring the time between the emission and reception. Ultrasonic waves can reflect off glass and liquid surfaces and return to the sensor head giving the Ultrasonic sensor the ability to detect transparent objects. The Ultrasonic sensor is so effective that factors like Light, Dust, Smoke, Mist, and the likes do not hinder its performance and it can also detect the presence of complex shaped objects.



All these components are available in the Invent Arduino Starter Kit.


The Ultrasonic sensor comes with VCC pin which is connected to 5v of the Arduino, Trig pin sends a signal and can be connected to any of the digital pins (in this case pin 9), when the signal finds an object it reflects back and is received by the Echo pin which can also be connected to any of the digital pins (in this case pin 10) and the GND pin is connected to GND on the Arduino Uno. Since we have connected an Led and a buzzer, when an object is detected, the Led comes on and the buzzer starts beeping.






const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 12;
const int ledPin = 13;
long duration;
int distance;
int safetyDistance;

void setup() {
  // put your setup code here, to run once:
 pinMode(trigPin, OUTPUT); 
 pinMode(echoPin, INPUT);
 pinMode(buzzerPin, OUTPUT);               //SET BUZZER AS OUTPUT.
 pinMode(ledPin, OUTPUT);                  //SET LED AS OUTPUT.


void loop() {
  // put your main code here, to run repeatedly:

 digitalWrite(trigPin, LOW);
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance= duration*0.034/2;
 safetyDistance = distance;
 if (safetyDistance <= 70){
 digitalWrite(buzzerPin, HIGH);
 digitalWrite(ledPin, HIGH);
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);





I hope that this tutorial has shown you all the steps on how to setup a Arduino distance sensor that makes use of the HC-SR04. If you have any feedback, tips or anything else then please don’t hesitate to leave a comment below.


0 0 vote
Article Rating
Would love your thoughts, please comment.x