Anda di halaman 1dari 3

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 t 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() {
Serial.begin(9600);
}
void loop(){
long duration;
float cm;
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
float microsecondsToCentimeters(long microseconds){
return (microseconds*0.034029)/2;
}

Anda mungkin juga menyukai