In my project my ultrasonic sensor is acting strange. I ran an ultrasonic sensor test code. When I bring the object closer to the sensor, it's measured distance increases and when I bring the object further away, it's measured distance decreases, as if it's inverted. It's measurements are also invalid: whenever I hold the object a foot away, it detects it as one meter.
I think that you should check the duration's of your pings that farther range reports as taking longer. This is the most important part of this post. The rest is nit-picking except for temperature and mach speed in hot or cold conditions.
Try using all type long variables and to avoid using floats...
1 meter at 340m/s = 1m / 340m/s = 0.002941...secs
= 2941 microsecs per meter one-way just to check values.
A 1 meter = 100 cm ping would take 5882 microsecs.
With this, calculating with all type long variables in 20C air should work well and be faster than using floats. Using .034 forces the whole calculation to be done with floats.
If we multiply duration by 100 and divide by 5882 we get cm's more precisely than cm = duration / 58.
It should get close to or the same as duration * .034 / 2, only a good bit faster on most Arduinos.
But be aware that the speed of sound is dependent on the temperature of the air. In cold air the speed is slower and in hot air it is faster. The difference is very small per degree. Humidity is a much smaller factor.
The Ping tutorial example says
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
What is this "object"
Those sensors work well with plain flat surfaces that are perpendicular to the sensor beam. Fuzzy and soft objects don't work so well, Objects at an angle don't work well either.
I changed it to A4 and A5 (so now the Trig is A4 and Echo is A5) and now it only works when I put the object very close to the ultrasonic sensor. What could this mean?