How To Use An Ultrasonic Sensor – Arduino Tutorial

sonar sensor

 

An Ultrasonic Sensor is a device that measures distance to an object using Sound Waves. It works by sending out a sound wave at ultrasonic frequency and waits for it to bounce back from the object. Then, the time delay between transmission of sound and receiving of the sound is used to calculate the distance.

It is done using the formula Distance = (Speed of sound * Time delay) / 2

We divide the distance formula by 2 because the sound waves travel a round trip i.e from the sensor and back to the sensor which doubles the actual distance.

The HC-SR04 is a typical ultrasonic sensor which is used in many projects such as obstacle detector and electronic distance measurement tapes. In this Instructable I’ll teach you how to interface the HC-SC04 with an Arduino Uno.

 

sonar sensor calculation

sonar sensor calculation

 

Components :

  • Arduino Uno
  • HC-SR04 Module
  • BreadBorad
  • Jumper wires

 

Connections:

sonar sensor connection

 

  • VCC – connect to 5V
  • GND – connect to ground
  • Trig – connect to an Arduino digital pin 12
  • Echo – connect to an Arduino digital pin 11

 

Example Code:

// defining the pins

const int trigPin = 12; 
const int echoPin = 11; 

// defining variables 

long duration; 
int distance;
int inch; 

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 in cm 
    distance= duration*0.034/2; 
   
    // Prints the distance on the Serial Monitor 
    Serial.print("Distance = ");
    Serial.print(dist);
    Serial.println(" cm");

    // Calculating the distance in inch 
    inch= duration*0.0133/2; 

    // Prints the distance on the Serial Monitor 
    Serial.print("Distance = "); 
    Serial.print(inch); 
    Serial.println(" inch");
 

}

 

Upload the Sketch and open the Serial monitor. Then you will see the distance in serial monitor.

 

Leave a Comment

(0 Comments)

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