For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance! The problem here is the int calculation, it should rather be performed as float. Now regarding accuracy, the library you are using has another issue here is how the distance in cm is calculated: int DistanceSRF04::getDistanceCentimeter() The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs. Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor in this situation, pulseIn() will return 36000us. So far we don't see any particular problem, that's fine. If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return: 3 x 2 / 340 x 1000000 = 17646 us PulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor. ![]() ![]() ![]() If we remove the averaging stuff (as _average is 1 by default), this boils down to: digitalWrite(_trigPin, LOW) Here is how the distance for roundtrip is calculated (code excerpts): long sum = 0 Just don't use that library, it seems poorly designed.
0 Comments
Leave a Reply. |