distance measurement

Basics of Ultrasonic Sensor HC-SR04

Image I purchased an ultrasonic sensor(HC-SR04) from ebay last week. I was searching the internet to learn how it works and found that there are very less elementary level examples so I decided to make one. An ultrasonic sensor first sends eight 40 Khz pulses, then detects the signal reflected by nearby obstacle and then based on time taken by pulse to return back it calculate the distance. Image It’s view angle is less (15 degrees or so) so it can only detect obstacle right in front of it. For people who are interested in the working and specification of this sensor click here to download its manual. Image In this example we”ll use HC-SR04 as proximity sensor to give a warning by glowing red LED if distance is less than 10 cm. This sensor is the essence of an Obstacle avoiding robot. The circuit diagram is:Image The code used is:

#define trigPin 13

#define echoPin 12

#define led 11

#define led2 10

void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(led, OUTPUT);

pinMode(led2, OUTPUT);


void loop() {

long duration, distance;

digitalWrite(trigPin, LOW);

// Added this line

delayMicroseconds(2); // Added this line

digitalWrite(trigPin, HIGH);

//delayMicroseconds(1000); – Removed this line

delayMicroseconds(10); // Added this line

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

if (distance < 10)

{ // This is where the LED On/Off happens


// When the Red condition is met, the Green LED //should turn off

digitalWrite(led2,LOW); }

else { digitalWrite(led,LOW);

digitalWrite(led2,HIGH); }

if (distance >= 200 || distance <= 0)

{ Serial.println(“Out of range”); }

else { Serial.print(distance);

Serial.println(” cm”);

} delay(500); }

If you want to see how actually this works then see the video below.