The easy way of Distance Measuring with Sonar Sensor (Using library)

The easy way of Distance Measuring with Sonar Sensor (Using library)

In this tutorial we’ll go through the demonstration of measuring distance using NewPing library with a sonar sensor and an arduino in just a couple of lines!

 

First lets see what we need for this tutorial !!

Well, for this tutorial we only need:
                 1) Arduino Uno or Arduino Mega
                 2) Ultrasonic Sonar sensor (HC-SR04 / SR05 / SR06)
                 3) NewPing Library
                 4) PC or Laptop (For now we’ll be showing this on windows only)

Arduino Uno                                               HC-SR04

Arduino_uno   HC-SR04

As intended, this tutorial will be short and simple. We won’t go through the fundamentals of how the sensor actually works and stuffs. So, if you want to (and you should) know the underlying mechanism, see this tutorial where everything is beautifully explained!!

Connection Schematics

First, connect everything like this diagram below.
schematicsSo,
Sensor | Arduino
VCC    >  5V
GND   >  GND
Trig     >   D12
Echo   >   D11


if you are using HC-SR05 , there is an extra pin “OUT”, just leave it alone.

The Code!!

Download the library from the link below.

Download New Ping Library

If you don’t know what arduino library is or how to use them, see my previous post about library installation.

Now connect your arduino to the computer and upload the following code!

#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11

NewPing sonar(TRIGGER_PIN, ECHO_PIN);

void setup() {
  Serial.begin(96500);
}

void loop() {
  delay(50);
  Serial.println(sonar.ping_cm());
}

And thats it!! Open your serial monitor and you should be seeing the distance of any object put in front of the Sensor in centimeters !!


Feel free to comment if you face trouble following any part of this tutorial or need additional help!

Thank You!


What are your thoughts?