I am tinkering with a simple Arduino sketch that detects distances using an ultrasonic sensor. From what I've understood, the trigger sends a ping. The echo listens for an echo that comes back to calculate the distance. This is measured in microseconds.
If that is correct, the question is, how can one determine inches and cm from that ping (that is given in microseconds)? Is this just basic math/physics, and is there just a basic formula for this?
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
This is the part that I'm having issues with. I want to divide ping time from microseconds to inches and then cm:
distance_in = duration ????;
distance_cm = duration ????;
Serial.print(distance_in);
Serial.print(" in, ");
Serial.print(distance_cm);
Serial.print(" cm");
Serial.println();
delay(1500);
}
Any help, with as much explanation as possible would be appreciated. I'm a newbie to Arduino (and not a heavy-lifter in math)
distance_cm = ( duration / 29 ) / 2;
distance_in = distance_cm * 0,393701;
1 m/s = 100/1000000 = 0.0001 cm/μs
343 m/s = 0.0001 * 343 = 0.0343 cm/μs
0.0343 cm/μs = 1 / 0.0343 = 29.155 μs/cm
Sound travels at 343 meters per second, which means it needs 29.155 microseconds per centimeter. So, we have to divide the duration by 29 and then by 2, because the sound has to travel the distance twice. It travels to the object and then back to the sensor.
1 cm = 0,393701 in