Distance Measurement Using Arduino and Ultrasonic Sensor (HC-SR04)
by techtronicharsh in Circuits > Arduino
722 Views, 0 Favorites, 0 Comments
Distance Measurement Using Arduino and Ultrasonic Sensor (HC-SR04)
In this Tutorial we will learn how the HC-SR04 Ultrasonic Sensor works and how to use it with the Arduino Board to measure the Distance. You can watch the following video or read the written tutorial below.
Supplies
How Ultrasonic Sensor Works ?
It emits an ultrasound at 40,000 Hz which travels through the air and if there is an object or obstacle in its path It will bounce back to the module. Considering the travel time and the speed of the sound you can calculate the distance.
The HC-SR04 Ultrasonic Module has 4 pins, Ground, Vcc, Trig and Echo. The Ground and the Vcc pins of the module needs to be connected to the Ground and the 5 volts pins on the Arduino Board respectively and the trig and echo pins to any Digital I/O pin on the Arduino Board.
In order to generate the ultrasound you need to set the Trig on a High State for 10 µs. That will send out an 8 cycle sonic burst which will travel at the speed sound and it will be received in the Echo pin. The Echo pin will output the time in microseconds the sound wave traveled.
Schematics :
Source Code :
/*
© Techtronic Harsh */
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)
const int trigPin = 9; const int echoPin = 10; long duration; int distanceCm, distanceInch;
void setup() { lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); lcd.setCursor(3,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Welcome to"); lcd.setCursor(0,1);
lcd.print("Techtronic Harsh"); delay(3000); lcd.clear();
}
void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); distanceCm= duration*0.034/2; distanceInch = duration*0.0133/2;
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed
lcd.print("Distance: "); // Prints "Distance" on the LCD lcd.print(distanceCm); // Prints the distance value from the sensor lcd.print("cm"); delay(30);
lcd.setCursor(0,1);
lcd.print("Distance: "); lcd.print(distanceInch); lcd.print("inch"); delay(30);
}
/*
© Techtronic Harsh */