Hello there!
I was looking at some code online for ultrasonic sensors and how to find out the distance in cm with them and i came across this code:
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; //cm/ms
I was just wondering why the time (duration) is devided by the speed when i thought to calculate distance you did speed x time...
Thank you!
But 29.1 isn't speed (distance per time) but the inverse (time per distance)
Speed of sound is 340.29 meters per second The inverse is 0.0029387 seconds per meter. That's 0.000029387 seconds per centimeter or 29.287 microseconds per centimeter.
Divide the microseconds by microseconds per centimeter to get centimeters. The "divide by 2" is done because the distance measured is round-trip.
You can keep an extra significant bit by skipping the divide by two and just dividing microseconds by 58.773 to get centimeters... or by 5.8773 to get millimeters.