distance-final

Arduino Distance Calculation Using Sonar

Arduino

Connect Arduino Uno as per below diagram

Distance-calc

Sonar system works in 2 step

  1. Create a ultrasonic sound to travel
  2. Receive the reflected sound as echo and calculate the time for sound traveling.

Below code show the result in centimeter.

Sample code is Here

 

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int sonarpw=7;

// defines variables
long duration;
int distance;
void setup() {

lcd.begin(16, 2);
lcd.clear();
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(sonarpw, OUTPUT);
Serial.begin(9600);
digitalWrite(sonarpw,HIGH);
}

void loop() {

lcd.setCursor(0, 0);
lcd.print(“Distance Calc”);
lcd.setCursor(0, 1);
lcd.print(“Distance:”);

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;

Serial.print(“Distance: “);
Serial.println(distance);
lcd.setCursor(10, 1);
lcd.print(distance);lcd.print(“cm “);
}

One thought on “Arduino Distance Calculation Using Sonar

Leave a Reply