Using HC SR 04

#define echoPin 7
#define trigPin 8

distance = duration/58.2;

This is the code that I used. It works fine but I wish to know whhere is this coming from " 58.2 " in distance = duration/58.2;. I know the formula but why 58.2, what does it represent?

Speed of sound in air is?

Please remember to use code tags when posting code.

its 340m/s.

Now, factor-in a round-trip (transmitter to object, object to receiver) time in microseconds, and you have your answer.

distance would be twice and would need division by 2, still not getting the term....

340343 m/s equal 2,91(5) seconds per km.

58,2 is microseconds it takes for the sound to travel back and forth per cm.

Gabriel_swe:
340343 m/s equal 2,91(5) seconds per km.

58,2 is microseconds it takes for the sound to travel back and forth per cm.

.< Thankyou so much...

The formula used in code is

distance = duration/58.2;

I want full explanation for why is it like that? I am getting to the answer but I don't think its through the correct method.

Distance = speed * time
speed = 340m/s

for calculations in microsecond and cm
speed = 340 * 100cm /1000 000 us

i.e. speed = 0.034cm/us

distance = 0.034 * duration ( in us) [cm]

so how is 58.2 coming from a direct approach ?

why do we need to do 1/340 ?

Don't know the sensor though and through but what I can see

It's
2 x Distance = speed x time

In the measured time the sound travels back and forth.

So
Distance = 1/2 x speed x time

And times (1/2 x 0,034) is the same as divide by 1/(1/2 x 0,034) = 58,8. Close enough. :wink: Datasheet even talks about using 58 because it's probably well within significance.

The sound has to travel back and forth, so you are missing a factor 2 in your computation,
343 m are a better value for the speed of sound in dry air of 20° C.

distance = 0.0343 * duration / 2
distance = 0.01715 * duration

1/0.01715 = 58.30

distance = duration / 58.30

Thankyou :slight_smile:

100% clear now...