This is Simple Example of Distance Measurement With Ultrasonic Sensor
Ultrasonic Sensor is simple Sensor that contains Trigger module and echo module. we can measure distance by ultrasonic sensor. this is brief explanation about how we Ultrasonic sensor works.
At first we enables Trigger pin which emits ultrasonic Sound, Then the sound falls on object in front of it and then reflects back then the we read (Measure ) time taken to this entire journey of sound by enabling echo pin. then we save that time taken into variable (In this code I use variable duration). Next task is simply to find Distance. (we can find distance simply by formula : Distance = speed X Time taken). so we take that variable 'Duration' and multiply it by 0.034 (Speed of sound) but this distance is double as sound reflects and come back with same path, so here we need to divide by 2 also. hence we use Distance = duration X 0.034/2
As a result we got our precise Distance.
int trig = 9 ;
int echo = 10 ;
void setup() {
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop() {
digitalWrite(trig, LOW);
delayMicroseconds(5);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
long duration = pulseIn(echo, HIGH);
int distance = duration * 0.034 / 2 ;
Serial.print("The Distance is : ");
Serial.println(distance);
}
Post a Comment