Distance Measurement Using Ultrasonic Sensor

Hello Friends , 
         Today we learn about how to measure the distance/Length, For this purpose we use the Ultrasonic Sensor  and for that sensor we can measure the distance.If you still not seen previous blog then click here.

BASIC

  • An ultrasonic sensor is an electronic device that measures the distance of a target object by emitting ultrasonic sound waves, and converts the reflected sound into an electrical signal. 
  • Ultrasonic waves travel faster than the speed of audible sound.

COMPONENTS

  1. Arduino Uno
  2. Ultrasonic Sensor(HC-SR04)
  3. Breadboard/ PC

CIRCUIT DIAGRAM


  1. +ve Terminal are connect with the +5v.
  2. -ve Terminal are connect with the Ground.
  3. Echo Terminal are connect with digital pin(make sure it is PWM pin).
  4. Trig Terminal are connect with the digital pin

CODE

//echo pin is a PWM pin so check it before connect...
const int trigpin=10; // declare trigpin
const int echopin =9; //declare echopin

long duration; //declare variable
int distance; //declare variable

void setup() {
  pinMode(trigpin, OUTPUT);  //define tri pin as output
  pinMode(echopin, INPUT);  //define echopin as input 
  Serial.begin(9600);  //baud rate define
}

void loop() {
    // Clears the trigPin condition 
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);
  
    // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigpin, HIGH);
  delayMicroseconds(2);

  digitalWrite(trigpin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
  duration =pulseIn(echopin, HIGH);
    //calculation for duration
  distance =duration/58.2;

    //Display distance on serial monitor  
  Serial.print("Distance");
  Serial.println(distance);
  delay(1000);
 
}

EXPLANATION

  1. In the loop first you have to make sure that the trigPin is clear so we have to set that pin on a LOW State for just 2 µs.
  2. Now for generating the ultrasound wave we have to set the trigPin on HIGH State for 2 µs. 
  3. Using the pulseIn()function you have to read the travel time and put that value into the variable “duration”. 
  4. This function has 2 parameters, the first one is the name of the echo pin and for the second one you can write either HIGH or LOW.
  5. In this case, HIGH means that the pulseIn() function will wait for the pin to go HIGH caused by the bounced sound wave and it will start timing, then it will wait for the pin to go LOW when the sound wave will end which will stop the timing. 
  6. At the end the function will return the length of the pulse in microseconds. 

This distance is in the "cm", and when distance is two far /null or too close then it is generate random value. 


So my dear friends I hope this content is very helpful and very useful in project development, If you have any doubt or questions then you can contact me.


Comments

Post a Comment