Arduino Uno Ultrasonic Distance Measurement Tutorial: From Setup to Code

by ganesh_20203 in Circuits > Arduino

770 Views, 3 Favorites, 0 Comments

Arduino Uno Ultrasonic Distance Measurement Tutorial: From Setup to Code

ultra_final.png
arduino uno R3.png
ultrasonic sensor.png

Unlock the power of precise distance measurement as we explore the seamless integration of an Arduino Uno with an ultrasonic sensor. I guide you through the steps to set up this dynamic duo, opening doors to a world of innovative projects and applications. Let's dive in!

Supplies

List of materials used:

1) Arduino UNO R3 - 1

2) HC-SR04 [Ultrasonic Sensor] - 1

3) UART cable - 1

Introduction

ultrasonic_info.png

Ultrasonic Sensor [HC-SR04]

  1. Principle: The ultrasonic sensor works on the principle of SONAR and RADAR system which is used to determine the distance to an object.
  2. Formulae used: distance = (speed*time)/2

Total distance = ( 343∗time of echo pulse)/2

3.Range: 2cm to 400 cm

Connections

ultra_final.png

Sensor connections:

1) Connect the 5V pin of Arduino Uno to the Vcc of the Ultrasonic Sensor.

2) Connect the gnd pin of Arduino Uno to the gnd of the Ultrasonic Sensor.

3) Connect pin 6 of Arduino Uno to the trig pin of the Ultrasonic Sensor.

4) Connect pin 5 of Arduino Uno to the echo pin of the Ultrasonic Sensor.

Code

// Pins

const int trig= 6;

const int echo= 5;

// Variables

int distance;

long duration;


void setup()

{

pinMode(trig, OUTPUT); // sets the trig as output

pinMode(echo, INPUT); //  sets the echo as input

Serial.begin(9600);   // sets the serial communication

}


void loop()

{  

digitalWrite(trig, LOW);

delayMicroseconds(2);

digitalWrite(trig, HIGH); // Sets the trigPin on HIGH state for 10 micro seconds

delayMicroseconds(10);

digitalWrite(trig, LOW);

duration = pulseIn(echo, HIGH);

distance = duration * 0.034 / 2;   // Reads the echoPin, returns the travel time in microseconds

Serial.print("Distance in cm: ");  // prints the distance in centimeters on the serial monitor

Serial.println(distance);  

}


Conclusion

To accomplish the desired result, follow the steps above. The fundamental illustration of using an Arduino Uno and an ultrasonic sensor is presented above. 

For any questions, contact: gy802655@gmail.com.