Distance Measuring using Ultra-sonic Sensor HC-SR04 using Arduino Uno Microcontroller with code

Distance Measuring using Ultra-sonic Sensor HC-SR04 using  Arduino Uno Microcontroller


Description

Used for measuring distance, object sensing, motion sensing etc.
The module sends eight 40Khz square wave pulses and automatically detects whether it receives the returning signal. If there is a signal returning,  a high level pulse is sent on the echo pin. The length of this pulse is the time it took the signal from first triggering to the return echo.

Pins

Vcc pin is given to + 5v
Trigger pin is for control
Echo is for receiving
Ground is connected to negative

Features of HC-SR04

  1. Working voltage is 5V DC.
  2. Static current is about  less than 2mA.
  3. Output signal is in the form of  Electric frequency signal, high level 5V, low level 0V.
  4. Sensor angle is nottl more than 15 degrees.
  5. Detection distance is in between  2cm-450cm.
  6. High precision Up to 3mm.
  7. Stable performance.
  8. Accurate distance measurement.
  9. High-density.
To see more about sensor : click here


The connections are as follows:

  • Vcc to 5V Pin of the Arduino.
  • Gnd to Gnd Pin of the Arduino.
  • Echo to Digital Pin 6.
  • Trig to Digital Pin 7.





Code for Circuit Diagram

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const int echoPin = 6;   // defining the pins

const int trigPin = 7;

// defining variables

long duration;
int distance;

void setup() {

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

pinMode(echoPin, INPUT); // Sets the echoPin as an Input

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

}

void loop() {

// Clears the trigPin

digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculating the distance

distance= duration*0.034/2;

// Prints the distance on the Serial Monitor

Serial.print("Distance: ");
Serial.println(distance);

}



If you still have any questions related to this article, then you can message me on my social media accounts.


Happy Learning
Thanks for Visiting