Ultrasonic Sensor-
Ultrasonic sensor is an electronic device which can calculate distance. It transmits ultrasonic waves and converts ultrasonic waves into electrical signal.
Ultrasonic sensor can be used in various projects from making smart dustbin to obstacle avoiding robots.
In this post, I will explain how to calculated distance using Ultrasonic sensor and Arduino Uno Microcontroller.
Calculate Distance using Ultrasonic Sensor and Arduino Uno Microcontroller
float duration;
void setup()
{
pinMode(2, OUTPUT);
pinMode(3, INPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(2, HIGH);
delayMicroseconds(10);
digitalWrite(2, LOW);\n
duration=pulseIn(3,HIGH);
distance = duration*0.034/2;
Serial.println(distance);
}
Explanation of Code Line by Line-
Line-1-This statement declares variable duration which stores time travelled by ultrasonic wave.
Line-2-setup() function is used to configure Pins for INPUT, OUTPUT, signal rate etc.
Line-3-Block of setup() function starts here.
Line-4-It indicates pin no. 2 is used for OUTPUT.
Line-5-It indicates pin no. 3 is used for INPUT.
Line-6-This statement sets signal rate 9600 Kbps.
Line-7-Block of setup() function ends here.
Line-8-Statements inside loop() function run forever.
Line-9-Block of loop() function starts here.
Line-10-digitalWrite(2, HIGH) statement will make trigger pin no. 2 supply voltage HIGH.
Line-11-This statement is for delay of 10 microseconds of Ultrasonic waves.
Line-12-digitalWrite(2, LOW) statement will make trigger pin no. 2 supply voltage LOW.
Line-13-PulseIn() function checks whether echo is HIGH, and returns propagation delay from sensor to object.
Line-14-distance = duration*0.034/2 statements calculates distance, where 0.034 dm/micros speed of ultrasonic wave.
Line-15-Serial.println(distance) prints distance on serial monitor.
Line-16-End of loop() function.