domenica 22 settembre 2013

Arduino ultrasonic distance measurement

Hi guys' today I'm here with a tutorial about interfacing arduino with ultrasonic distance meter like the HC-SR04.
First of all, the theory:

If we know that the sound take a time to reach the obstacle and come back and that
speed s is equal to s=d/t where d is the distance then d=s*t .
We consider that speed of sound is 340.29 meters/seconds that is equal to
0.034029 centimeters/microseconds.

Now let's see the hardware parts, which is very simple:

To start measuring distance you just have to upload this code to the arduino
int trigPin = 2;
int echoPin = 4;

void setup() {

void loop(){
  long duration;
  float cm;
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  cm = microsecondsToCentimeters(duration);
float microsecondsToCentimeters(long microseconds){
  return (microseconds*0.034029)/2;

Here is a video of me testing this project:

I hope you like this post, if you have any question please comment or send me an email to


1 commento:

  1. Hi.....nice work ....can we use 16x2 LCd to display the distance ..... if you have time please give code for LCD display ...regards, Ashok Shah