Well, actually, I forgot about the internal data filter. Leaving the sensor always powered will give time for that to come into play. I don’t know if it will help any, though.
Some thing else I thought about in your code: Even though you’re delaying for a second between calls to the
function, you were actually parsing and keeping the first 10 readings the sensor took after power on (about 166ms apart) and just processing them 1 second apart. That’s because as long as the sonar is sending data (which is continuously while it is powered) and you’re listening to it with SoftwareSerial, the characters are being stored in the buffer. Once the buffer is full, they just get thrown away. Nothing comes out of the buffer until you
it. When you do read it, you’re reading out in the order they were placed into the buffer, even if they were placed there a while ago. The fix I suggested for the sleep will also fix this because the end() will dump the buffer and it will be re-created empty at the begin().
I doubt going up to 25 attempts will make much of a difference.